Skip to content

Latest commit

 

History

History
31 lines (27 loc) · 903 Bytes

File metadata and controls

31 lines (27 loc) · 903 Bytes

题目地址

https://leetcode-cn.com/problems/number-of-islands/

思路

递归
判断岛屿的上下左右是否有相邻岛屿,并将相邻的岛屿置为0,在接着重复该函数。

from typing import List


class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        nr = len(grid)
        if nr == 0:
            return 0
        nc = len(grid[0])
        num = 0
        for i in range(nr):
            for j in range(nc):
                if grid[i][j] == "1":
                    num += 1
                    self.recursion(grid, i, j)
        return num

    def recursion(self, grid, x, y):
        grid[x][y] = 0
        nr, nc = len(grid), len(grid[0])
        for x, y in [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]:
            if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == "1":
                self.recursion(grid, x, y)