Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
Solution:
Traversing the grid.
When we meet ‘1’, Island count plus one. Using DFS to revise all adjacent island to ‘0’.
Continuing to traverse the grid. When we meet the next ‘1’, do the same thing.
class Solution {
int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int numIslands(char[][] grid) {
int nr = grid.length;
if (grid == null || nr == 0) {
return 0;
}
int nc = grid[0].length;
int numIslands = 0;
for (int r = 0; r < nr; r++) {
for (int c = 0; c < nc; c++) {
if (grid[r][c] == '1') {
numIslands++;
dfs(grid, r, c);
}
}
}
return numIslands;
}
public void dfs(char[][] grid, int r, int c) {
int nr = grid.length;
int nc = grid[0].length;
if (r < 0 || r > nr - 1 || c < 0 || c > nc - 1 || grid[r][c] != '1') {
return;
}
grid[r][c] = '0';
for (int[] d : dir) {
dfs(grid, r + d[0], c + d[1]);
}
}
}
|