LeetCode 130, 200, 694, 695, 733 (“岛” 系列): DFS方法题解(python)
描述:
Leetcode之中有一类题目,给定一个用二维数组表示的类似的迷宫/围棋/岛屿, 然后有诸如找有多少个岛屿(130, 200),或者有多少个不一样的岛屿(694),或者最大岛屿的面积(695)之类的要求。这些题目大体上存在三种解法: DFS(深度优先搜索),BFS(广度优先搜索),Union Find
。在这里总结一下岛屿类问题的DFS
方法求解。
链接: 130: Surrounded Region.
链接: 200: Number of Islands.
链接: 694: Number of Distinct Islands.
链接: 695: Max Area of Island.
链接: 733: Flood Fill.
200: Number of Islands.
问题描述:
给了一个二维数组,指定‘0’作为海水,‘1’作为陆地。问这个数组里有多少个岛屿。要求边境都是海水,并且连着的‘1’是作为一个岛屿。
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
思路:
这里使用dfs,找到所有由‘1’组成的路径。然后有多少个路径就有多少个岛屿。这是十分基础的DFS用法。
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
res+= 1
return res
def dfs(self, grid, i, j):
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] =='0':
return 函数退出的条件
grid[i][j] = '0' 函数的操作(函数的目的)
self.dfs(grid, i, j-1) 递归
self.dfs(grid, i, j+1) 递归
self.dfs(grid, i-1, j) 递归
self.dfs(grid, i+1, j) 递归
总结:
这道题dfs函数的写法几乎可以认为是这一类题目的dfs写法:先判断退出->函数操作(目的)-> 然后向四个方向递归即可。