Python中的岛屿数量
假设我们有一个网格,其中有一些0和一些1。我们需要计算岛屿的数量。岛屿是指被水包围并通过水平或垂直连接相邻陆地形成的地方。我们可以假设网格的所有四个边缘都被水包围。
假设网格如下:
1 | 1 | 0 | 0 | 0 |
1 | 1 | 0 | 0 | 0 |
0 | 0 | 1 | 0 | 0 |
0 | 0 | 0 | 1 | 1 |
共有三个岛屿。
为了解决这个问题,我们将遵循以下步骤:
- 将会有两种方法,一种用于计算岛屿数量,称为numIslands(),另一种为makeWater()。makeWater()将如下所示:
- 如果网格的行数为0,则返回0
- n = 行数,m = 列数,ans = 0
- 对于i从0到n-1
- 对于j从0到m
- 如果grid[i, j] = 1,则ans = ans + 1
- makeWater(i, j, n, m, grid)
- 对于j从0到m
- makeWater()将接收索引i、j、行数n、列数m和网格
- 如果i < 0 或 j < 0 或 i >= n 或 j >= m,则从此方法返回
- 如果grid[i, j] = 0,则返回;否则,将grid[i, j]设置为0
- 调用makeWater(i + 1, j, n, m, grid)
- 调用makeWater(i, j + 1, n, m, grid)
让我们看下面的实现来更好地理解:
示例
class Solution(object): def numIslands(self, grid): if len(grid) == 0: return 0 n= len(grid) m = len(grid[0]) ans = 0 for i in range(n): for j in range(m): if grid[i][j] == "1": ans+=1 self.make_water(i,j,n,m,grid) return ans def make_water(self,i,j,n,m,grid): if i<0 or j<0 or i>=n or j>=m: return if grid[i][j] == "0": return else: grid[i][j]="0" self.make_water(i+1,j,n,m,grid) self.make_water(i,j+1,n,m,grid) self.make_water(i-1,j,n,m,grid) self.make_water(i,j-1,n,m,grid) ob1 = Solution() print(ob1.numIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"], ["0","0","0","1","1"]]))
输入
[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
输出
3
广告