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, 遍历grid, 如果找到小岛, 则将它所有连接的岛标记为#, 并且计数加一.
Time: O(m*n)
Space: O(1)
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid: return 0
count = 0
r, c = len(grid), len(grid[0])
for i in range(r):
for j in range(c):
# if we meet the island, mark all the adjacent islands
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
# base case
if not (0 <= i<len(grid) and 0<= j < len(grid[0]) and grid[i][j] == '1'):
return
grid[i][j] = '#'
self.dfs(grid, i-1, j)
self.dfs(grid, i+1, j)
self.dfs(grid, i, j-1)
self.dfs(grid, i, j+1)