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
可以用DFS实现,也可以用BFS实现。有一点核心思想就行,需要能标准出node已经被访问过。
DFS:
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length;
if (m == 0) return 0;
int n = grid[0].length;
int num = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++num;
helper(grid, i, j);
}
}
}
return num;
}
private void helper (char[][]grid, int r, int c) {
int m = grid.length;
if (m == 0) return;
int n = grid[0].length;
if (r < 0 || r > m-1 || c < 0 || c > n-1 || grid[r][c] == '0') {
return;
}
grid[r][c] = '0';
helper(grid, r+1, c);
helper(grid, r-1, c);
helper(grid, r, c+1);
helper(grid, r, c-1);
}
}
BFS
/**
* 这个BFS 流程基本上和Walls and Gates的BFS实现方案差不多,只是在搜索的过程中做的事不一样而已
*
**/
class Solution {
private static final List<int[]> DIRECTIONS = Arrays.asList(
new int[]{1, 0},
new int[] {-1, 0},
new int[] {0, 1},
new int[] {0, -1});
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0)
return 0;
int rowNum = grid.length;
int colNum = grid[0].length;
int num_islands = 0;
Queue<int[]> queue = new LinkedList();
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
if (grid[i][j] == '1') {
num_islands++;
grid[i][j] = '0';
queue.offer(new int[]{i,j});
while (!queue.isEmpty()) {
int[] point = queue.poll();
int row = point[0];
int col = point[1];
for (int[] direction : DIRECTIONS) {
int r = row + direction[0];
int c = col + direction[1];
if (r < 0 || r > rowNum-1 || c < 0 || c > colNum-1 || grid[r][c]=='0')
continue;
grid[r][c] = '0';
queue.offer(new int[]{r,c});
}
}
}
}
}
return num_islands;
}
}