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
This is a typical DFS problem. What we need to do is to go as deep as possible until we either run out of bound or the position we visit is not an island. When implementing DFS code, there are usually two ways. You can either have a constant array to store four directions, or you just need to call the DFS function recursively. Here is the Java version code.
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int m = grid.length, n = grid[0].length;
int num_of_islands = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
num_of_islands++;
dfs(grid, i, j, m, n);
}
}
}
return num_of_islands;
}
private void dfs(char[][] grid, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') return;
grid[i][j] = '0';
dfs(grid, i - 1, j, m, n);
dfs(grid, i + 1, j, m, n);
dfs(grid, i, j - 1, m, n);
dfs(grid, i, j + 1, m, n);
}
}