孤岛数量的递归解决方案

时间:2019-04-17 05:26:52

标签: python algorithm

我正在尝试解决问题Number of Islands - LeetCode

  

给定'1'(土地)和'0'(水)的二维网格图,计算岛屿的数量。一个岛屿被水包围,是通过水平或垂直连接相邻的陆地而形成的。您可能会假设网格的所有四个边缘都被水包围了。

     

示例1:

Input:
11110
11010
11000
00000

Output: 1
     

示例2:

Input:
11000
11000
00100
00011

Output: 3

可接受的解决方案是:

#Recursively solution 
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        step = 0
        r, c = len(grid), len(grid[0])
        visited = [[False for _ in range(c)] for _ in range(r)]
        for i in range(r):
            for j in range(c):
                if grid[i][j] == "1" and not visited[i][j]:
                    step += 1
                    self.dfs(grid, i, j, visited)
        return step

    def dfs(self, grid, i, j, visited):
        if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1' or visited[i][j]:        
            return 
        visited[i][j] = True
        self.dfs(grid, i+1, j, visited)
        self.dfs(grid, i-1, j, visited)
        self.dfs(grid, i, j+1, visited)
        self.dfs(grid, i, j-1, visited)

解决方案结合了递归和迭代功能。

如何仅通过递归来解决问题?

1 个答案:

答案 0 :(得分:1)

所有您需要做的就是在到达行尾时将循环更改为递归函数,该递归函数从某个坐标(r,c)到下一个坐标(r,c + 1)或(r + 1,0)。

示例代码:

def numIslands(grid, row, col):
    if not grid: return 0

    ans = 0

    if grid[row][col]==1:
        ans+=1
        dfs(grid,row,col)

    col+=1
    if col == len(grid[0]):
        col=0
        row+=1

    if row == len(grid):
        return ans

    return ans + numIslands(grid, row, col)

def dfs(grid, i, j):
    if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:        
        return 
    grid[i][j] = -1
    dfs(grid, i+1, j)
    dfs(grid, i-1, j)
    dfs(grid, i, j+1)
    dfs(grid, i, j-1)


print(numIslands([
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1]
],0,0))