zoukankan      html  css  js  c++  java
  • 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~
  • 相关阅读:
    Shell编程常用
    毕设问答
    《如何高效学习》
    《如何阅读一本书》(未完)
    《牧羊少年奇幻之旅》
    2019.04月总结
    上周还是合意的,且找到了一定的遵循4.6-4.12

    错误和异常
    数据结构
  • 原文地址:https://www.cnblogs.com/jkmiao/p/4953044.html
Copyright © 2011-2022 走看看