Number of Islands
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
Python3 Solution:
思路:
利用深度优先搜索(DFS),统计共有多少个连通分量
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rSize, cSize, res = len(grid), len(grid[0]), 0
def dfs(i, j):
grid[i][j] = "0"
if i>0 and grid[i-1][j] == "1":
dfs(i-1, j)
if j>0 and grid[i][j-1] == "1":
dfs(i, j-1)
if i+1<rSize and grid[i+1][j] == "1":
dfs(i+1, j)
if j+1<cSize and grid[i][j+1] == "1":
dfs(i, j+1)
for i in range(rSize):
for j in range(cSize):
if grid[i][j] == "1":
dfs(i, j)
res += 1
return res