Leetcode[200] Number of Islands
16 Nov 2015###Task1 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:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
Answer: 3
###Python
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return 0
M = len(grid)
N = len(grid[0])
ret = 0
for i in range(M):
for j in range(N):
if grid[i][j] == '1':
ret += 1
self.merge(grid, i, j, M, N)
return ret
def merge(self, grid, i, j, M, N):
if i < 0 or i >= M or j < 0 or j >= N:
return
if grid[i][j] != '1':
return
grid[i][j] = '#'
self.merge(grid, i + 1, j, M, N)
self.merge(grid, i - 1, j, M, N)
self.merge(grid, i, j + 1, M, N)
self.merge(grid, i, j - 1, M, N)
###Java
public class Solution {
public void merge(char[][] grid, int i, int j, int row, int col) {
if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] != '1') {
return;
}
grid[i][j] = '0';
merge(grid, i + 1, j, row, col);
merge(grid, i - 1, j, row, col);
merge(grid, i, j - 1, row, col);
merge(grid, i, j + 1, row, col);
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int row = grid.length;
int col = grid[0].length;
int res = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1') {
res++;
merge(grid, i, j, row, col);
}
}
}
return res;
}
}
###Points
- DFS
FloodFill,BFS(广度优先搜索)或者DFS(深度优先搜索)均可。