-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfIslands.java
More file actions
31 lines (26 loc) · 1004 Bytes
/
NumberOfIslands.java
File metadata and controls
31 lines (26 loc) · 1004 Bytes
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
//https://leetcode.com/problems/number-of-islands/description/
public class NumberOfIslands {
public int numIsland(char[][] grid) {
int count = 0;
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[0].length; j++)
if (grid[i][j] == '1') {
count++;
removeIsland(i, j, grid);
}
return count;
}
private void removeIsland(int i, int j, char[][] grid) {
// if we go off the grid, this should not add to the island
if (i >= 0 && j >= 0 && i < grid.length && j < grid[0].length) {
if (grid[i][j] == '1') {
grid[i][j] = '0'; // mark as visited
// remove the 1 to a search of surrounding grid points
removeIsland(i + 1, j, grid);
removeIsland(i - 1, j, grid);
removeIsland(i, j + 1, grid);
removeIsland(i, j - 1, grid);
}
}
}
}