dfs would mark every connected land 1; then count++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private int m;
private int n;

public int numIslands(char[][] grid) {
if (grid.length == 0 || grid[0].length == 0) return 0;
m = grid.length;
n = grid[0].length;
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}

public void dfs(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == '0') return;
grid[i][j] = '0';
dfs(grid, i-1, j); dfs(grid, i+1, j); dfs(grid, i, j-1); dfs(grid, i, j+1);
}

If count is outside dfs, i.e. outside inner for loop, then each row would make count++: a count == grid.length: meaningless, not dfs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private int m;
private int n;

public int numIslands(char[][] grid) {
if (grid.length == 0 || grid[0].length == 0) return 0;
m = grid.length;
n = grid[0].length;
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
}
count++;
}
}
return count;
}

public void dfs(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == '0') return;
grid[i][j] = '0';
dfs(grid, i-1, j); dfs(grid, i+1, j); dfs(grid, i, j-1); dfs(grid, i, j+1);
}