深度优先搜索

深度优先搜索

from IPython.display import Image
Image(filename="./data/4_01.png",width=800,height=960)

output_1_0.png

一.最大岛屿

0 0 0 0 1 1 0
0 1 1 0 1 1 0
0 1 1 0 1 1 0
0 0 1 0 0 1 1
0 0 0 0 0 0 0
0 0 1 1 0 0 0
0 0 0 1 0 0 1
class Solution(object):
    def __init__(self):
        pass
    
    def maxAreaOfIsland(self,grid):
        # 存储最大岛屿的面积
        self.maxArea=0
        # 存储地图的行数
        row=len(grid)
        # 存储地图的列数
        col=len(grid[0])
        
        for i in range(row):
            # 开始从左到右,从上到下地搜索岛屿
            for j in range(col):
                if grid[i][j]==1:
                    # 测量岛屿面积
                    current=1
                    self.dfs(i,j,current,grid)
                    
        return self.maxArea
    
    def dfs(self,k,z,current,grid):
        # 第一处标记此处为已访问
        grid[k][z]=2
        
        if k>0 and grid[k-1][z]==1:
            current=self.dfs(k-1,z,current+1,grid)
            
        if k<(len(grid)-1) and grid[k+1][z]==1:
            current=self.dfs(k+1,z,current+1,grid)
            
        if z>0 and grid[k][z-1]==1:
            current=self.dfs(k,z-1,current+1,grid)
            
        if z<(len(grid[0])-1) and grid[k][z+1]==1:
            current=self.dfs(k,z+1,current+1,grid)
        
        # 更新最大面积变量
        self.maxArea=max(self.maxArea,current)
        return current
grid=[
    [0,0,0,0,1,1,0],
    [0,1,1,0,1,1,0],
    [0,1,1,0,0,0,0],
    [0,0,1,0,0,1,1],
    [0,0,0,0,0,0,0],
    [0,0,1,1,0,0,0],
    [0,0,0,1,0,0,1]
]

Solution().maxAreaOfIsland(grid)
5

深度优先算法的本质就是"一条路走到黑",直到不能走才换另一条路

原文地址:https://www.cnblogs.com/LQ6H/p/12940560.html