【问题标题】:Number of Island leetcode python孤岛数 leetcode python
【发布时间】:2020-07-31 21:43:41
【问题描述】:

问题如下:给定一个由“1”(陆地)和“0”(水)组成的二维网格图,计算岛屿的数量。岛屿四面环水,由相邻陆地水平或垂直连接而成。您可以假设网格的所有四个边缘都被水包围。

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        # use dfs / replace the island's elements with a sign "."
        a = len(grid)
        b = len(grid[0])
        num = 0


        for i in range(0 , a-1):
            for j in range(0 , b-1):
                if grid[i][j] == '1':
                    num += 1
                    self.dfs(grid , i , j)

        return num

    def dfs(self, grid , x , y):

        if x < 0 or y < 0 or x >= len(grid[0]) or y >= len(grid) or grid[x][y] == '0' or grid[x][y] == ".": # if out of boundary
            return

        grid[x][y] = "."        
        # if 1's has only one neighbor

        self.dfs(grid , x-1 , y)   # check 4 edges of water
        self.dfs(grid, x+1 , y)
        self.dfs(grid , x , y+1)
        self.dfs(grid , x , y- 1)

此代码仅适用于以下输出:[["1","1","1","1","0"],["1","1","0","1" ,"0"],["1","1","0","0","0"],["0","0","0","0","0"]]

但是,它不适用于此输出:[["1","1","0","0","0"],["1","1","0"," 0","0"],["0","0","1","0","0"],["0","0","0","1","1" ]]

我正在尝试使用 dfs 方法。因此,如果 x 在数组中,函数 dfs 将从 4 个边检查相邻元素是否为“1”,如果为“1”,则将其替换为“.”。否则,如果元素为“0”,则递归循环停止。一旦所有可能的组合的所有递归循环停止,计数就会增加 1。然后程序运行以查找其他“X”。

但是,该程序无法正常运行。因此,谁能帮我找出这段代码中的问题?

【问题讨论】:

  • range 的结尾被排除在该范围之外,因此请尝试仅将 a-1b-1 替换为 ab
  • 我试过了,但是列表索引超出了第二个输出的范围
  • 看起来这个条件应该是相反的:x &gt;= len(grid[0]) or y &gt;= len(grid)(你使用x作为“行”和y作为“列”)
  • 我也试过了,但它说 b = len(grid[0]) 不知何故超出了索引范围

标签: python recursion matrix multidimensional-array depth-first-search


【解决方案1】:

不幸的是,我找不到你的代码有什么问题,我自己做了一个,它有点不同但它有效,也许它可以帮助你找到问题

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        
        def is_land(grid, next_loc):
            
            (x, y) = next_loc
            
            grid[x][y] = '0'
            
            if x+1 < rows and grid[x+1][y] == '1':
                grid = is_land(grid, (x+1, y))
            
            if x - 1 >= 0 and grid[x-1][y] == '1':
                grid = is_land(grid, (x-1, y))
            
            if y+1 < cols and grid[x][y+1] == '1':
                grid = is_land(grid, (x, y+1))
            
            if y-1 >= 0 and grid[x][y-1] == '1':
                grid = is_land(grid, (x, y-1))
            
            return grid
        
        rows = len(grid)
        cols = len(grid[0])
        ans = 0
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == '1':
                    grid = is_land(grid, (row, col))
                    ans += 1
        return ans

【讨论】:

  • 感谢您的解决方案
猜你喜欢
  • 2016-11-03
  • 2021-07-30
  • 2021-03-07
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多