Bootstrap

【hot100篇-python刷题记录】【岛屿数量】

R5-图论

遍历整个二维数组,遇到1就横竖扩展把1变为0,同时计数

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        m=len(grid)
        n=len(grid[0])
        ret=0
        #横竖扩展变1为0的操作函数
        def dfs(i,j):
            grid[i][j]="0"
            for x,y in [[0,1],[1,0],[0,-1],[-1,0]]:
                tmp_i=i+x
                tmp_j=j+y
                #继续深度查找
                if 0<=tmp_i<m and 0<=tmp_j<n and grid[tmp_i][tmp_j]=="1":
                    dfs(tmp_i,tmp_j)
                            
        for i in range(m):
            for j in range(n):
                if grid[i][j]=="1":
                    dfs(i,j)
                    ret+=1
        return ret

        

 

;