Repository navigation
Expand file tree
/
Copy pathIslandsRecursive.java
More file actions
51 lines (42 loc) Β· 1.48 KB
/
Copy pathIslandsRecursive.java
File metadata and controls
51 lines (42 loc) Β· 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package graph.islands;
import annotation.DepthFirstSearch;
/**
* Time Complexity: O(m x n) <br />
* Space Complexity: O(m x n) for the recursive call stack itself. Sometimes this gets incorrectly ignored
* to conclude it must be O(1) since input grid gets updated to keep track of visited islands by drowning them <br />
*
* @see <a href="https://leetcode.com/problems/number-of-islands/description/">200. Number of Islands</a>
* @see IslandsIterative
* @see IslandsVisitedSet
*/
@DepthFirstSearch
public class IslandsRecursive {
static final char CELL_ISLAND = '1';
static final char CELL_WATER = '0';
private char[][] grid; // Small optimization to avoid passing grid as a method parameter on each call of visit()
public int numIslands(char[][] grid) {
int count = 0;
this.grid = grid;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == CELL_ISLAND) {
count++;
visit(i, j);
}
}
}
return count;
}
private void visit(int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length) {
return;
}
if (grid[i][j] == CELL_ISLAND) {
grid[i][j] = CELL_WATER; // mark as visited (aka drown the island)
visit(i - 1, j);
visit(i + 1, j);
visit(i, j - 1);
visit(i, j + 1);
}
}
}