Given a 2D grid of '1'
(land) and (water), count the number of islands. '0'
An island is surrounded by water, and it is connected by adjacent land, either horizontally or vertically. You can assume that the mesh is surrounded by water on all four sides.
Example 1:
Input:
11110
11010
11000
00000output: 1
Example 2:
Input:
11000
11000
00100
00011output: 3
Traverse the two-dimensional array, when encountering a position with a value of 1, start a deep search from that position. During the deep search process, when a value of 1 is encountered, change 1 to 0.
public int numIslands(char[][] grid) {
if (grid.length <= 0 || grid[0].length <= 0)
return 0;
int ans = 0;
int rowNum = grid.length;
int colNum = grid[0].length;
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
if (grid[i][j] == '1') {
dfs(i, j, grid);
ans++;
}
}
}
return ans;
}
public void dfs(int i, int j, char[][] grid) {
int rowNum = grid.length;
int colNum = grid[0].length;
if (i < 0 || i >= rowNum || j < 0 || j >= colNum || grid[i][j] == '0')
return;
grid[i][j] = '0';
dfs(i + 1, j, grid);
dfs(i - 1, j, grid);
dfs(i, j + 1, grid);
dfs(i, j - 1, grid);
}