- class Solution:
- def numIslands(self, grid: List[List[str]]) -> int:
- res=0
- row=len(grid)
- col=len(grid[0])
- def bfs(i,j):
- if i<0 or j<0 or i>=row or j>=col or grid[i][j]=='0':
- return #递归调用没有判断grid[i][j]=='0',故需要判断
- grid[i][j]='0'
- bfs(i+1,j)
- bfs(i-1,j)
- bfs(i,j-1)
- bfs(i,j+1)
- for i in range(row):
- for j in range(col):
- if grid[i][j]=='1':
- res+=1 #dfs时结果加1
- bfs(i,j)
- return res
题目是字符数组不是数字数组,7行16行易错
利用dfs消除同一片陆地,主函数调用dfs次数即为所求