Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class IslandMap implements Map {
- private boolean[][] map;
- public IslandMap(boolean[][] map) {
- this.map = map;
- }
- /* Returns a number of isolated "islands" (groups of "lands") on the map,
- * where 'true' means land, 'false' means sea.
- * Creates a copy of a map not to change the actual map.
- *
- * Time complexity: O(N),
- * Space complexity: O(N),
- * where N is a number of cells in a map
- *
- */
- public int countIslands() {
- boolean[][] mapCopy = copyMap(map);
- int counter = 0;
- for (int i = 0; i < map.length; i++) {
- for (int j = 0; j < map[i].length; j++) {
- if (mapCopy[i][j]) {
- counter++;
- markIslandAsVisited(mapCopy, i, j);
- }
- }
- }
- return counter;
- }
- /*
- * Marks a piece of land from the map as sea not to count the same island several times
- * Recursively checks adjacent cells and marks them as water
- *
- * Time complexity: O(N),
- * Space complexity: O(N)
- * where N is a number of cells in a map
- *
- * @param map is a map marked with seas and lands
- * @param i is a row where current cell is located
- * @param j is a column where current cell is located
- */
- private void markIslandAsVisited(boolean[][] map, int i, int j) {
- if (!coordinateIsValid(i, j)) {
- return;
- }
- if (!map[i][j]) {
- return;
- }
- map[i][j] = false;
- markAdjacentCells(map, i, j);
- }
- private void markAdjacentCells(boolean[][] map, int i, int j) {
- markIslandAsVisited(map, i+1, j);
- markIslandAsVisited(map, i-1, j);
- markIslandAsVisited(map, i, j+1);
- markIslandAsVisited(map, i, j-1);
- }
- private static boolean[][] copyMap(boolean[][] map) {
- boolean[][] copyMap = new boolean[map.length][map[0].length];
- for (int i = 0; i < copyMap.length; i++) {
- for (int j = 0; j < copyMap[i].length ; j++) {
- copyMap[i][j] = map[i][j];
- }
- }
- return copyMap;
- }
- private boolean coordinateIsValid(int i, int j) {
- return (i >= 0 && j >= 0 && i < map.length && j < map[i].length);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement