• Number of Islands


    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

    Example 1:

    11110
    11010
    11000
    00000

    Answer: 1

    Example 2:

    11000
    11000
    00100
    00011

    Answer: 3

    DFS 遍历,将1周围的1都变为0,最后数下有多少个1即可。

    class Solution(object):
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            if not len(grid):
                return 0
            res = 0
            m,n = len(grid),len(grid[0])
            for i in range(m):
                for j in range(n):
                    if grid[i][j]=='1':
                        res += 1
                        self.dfs(grid,i,j,m,n)
            return res
            
            
            
        def dfs(self,grid,i,j,m,n):
            if i<0 or i>=m or j<0 or j>=n: return
            if grid[i][j]=='1':
                grid[i][j]='0'
                dz = zip([1,0,-1,0],[0,1,0,-1])
                for px,py in dz:
                    self.dfs(grid,i+px,j+py,m,n)
                    
                    
    每天一小步,人生一大步!Good luck~
  • 相关阅读:
    nsis打包
    学习记录:ST表
    学习记录:快速幂
    学习记录:哈夫曼树
    学习记录:二叉树
    学习记录:康托展开 与 逆康托展开
    堆排序简介
    动态规划水题集
    lower_bound( ) 与 upper_bound( )
    琐碎的一点技巧
  • 原文地址:https://www.cnblogs.com/jkmiao/p/4953044.html
Copyright © 2020-2023  润新知