基本思路:
深度优先遍历图的方法是,从图中某顶点v出发:
(1)访问顶点v;
(2)依次从v的未被访问的邻接点出发,对图进行深度优先遍历;直至图中和v有路径相通的顶点都被访问;
(3)若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。
例1:图像渲染
输入: image = [[1,1,1],[1,1,0],[1,0,1]],sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析: 在图像的正中间,(坐标(sr,sc)=(1,1)),在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,因为它不是在上下左右四个方向上与初始点相连的像素点。
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
oldColor = image[sr][sc]
if oldColor == newColor:
return image
def dfs(image,i,j):
if i < 0 or i > len(image)-1 or j < 0 or j > len(image[0])-1 or image[i][j] != oldColor:
return
image[i][j] = newColor
dfs(image,i+1,j)
dfs(image,i-1,j)
dfs(image,i,j+1)
dfs(image,i,j-1)
return image
return dfs(image,sr,sc)
例2:岛屿数量
给一个01矩阵,1代表是陆地,0代表海洋, 如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
岛屿: 相邻陆地可以组成一个岛屿(相邻:上下左右) 判断岛屿个数。
例如:
输入
[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]
对应的输出为3
class Solution:
def maxNumOfIsland(self , grid: List[List[int]]) -> int:
def dfs(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
dfs(grid,i+1,j)
dfs(grid,i-1,j)
dfs(grid,i,j+1)
dfs(grid,i,j-1)
island = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
island += 1
dfs(grid,i,j)
return island
例3:岛屿最大面积
输入:grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
输出:6
解释:答案不应该是 11 ,因为岛屿只能包含水平或垂直这四个方向上的 1 。
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_island = 0
def dfs(grid,i,j,res):
if i < 0 or i > len(grid)-1 or j < 0 or j > len(grid[0])-1 or grid[i][j] == 0:
return res
res += grid[i][j]
grid[i][j] = 0
res = dfs(grid,i+1,j,res)
res = dfs(grid,i-1,j,res)
res = dfs(grid,i,j+1,res)
res = dfs(grid,i,j-1,res)
return res
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
max_island = max(max_island,dfs(grid,i,j,0))
return max_island