leet200. 岛屿的个数

题目:

给定 '1'(陆地)和 '0'(水)的二维网格图,计算岛屿的数量。一个岛被水包围,并且通过水平或垂直连接相邻的陆地而形成。你可以假设网格的四个边均被水包围。

示例 1:

11110
11010
11000
00000

答案: 1

示例 2:

11000
11000
00100
00011

答案: 3


分析:

  1. 遍历grid,当当前位置值为1时,岛的数量加1,为了防止重复计数,将遍历后的位置改为0或1以外的值,递归处理当前位置相邻4个位置

代码:

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if not grid:
            return 0
        dirction = [(-1,0),(1,0),(0,-1),(0,1)]
        self.widthGrid = len(grid[0])
        self.heightGrid = len(grid)
        self.islandNums = 0
        def validNab(location):
            dirction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
            narbLoc = []
            narbLst = [(location[0] + x[0],location[1] + x[1]) for x in dirction]
            for p in narbLst:
                if 0 <= p[0] < self.heightGrid and 0 <= p[1] < self.widthGrid:
                    narbLoc.append(p)
            return narbLoc
        def travelIsland(location,g = grid):
            if g[location[0]][location[1]] == '1':
                g[location[0]][location[1]] = str(self.islandNums + 1)
                map(travelIsland,validNab(location))
        for i,l in enumerate(grid):
            for j,val in enumerate(l):
                if val == '1':
                    self.islandNums += 1
                    travelIsland((i,j))
        return self.islandNums

思考:



你可能感兴趣的:(Python)