封面

LeetCode 题解 · 岛屿数量

笔记日期
# LeetCode
# Python
# 深度优先搜索

方格纸上数岛,难点是绕了一圈又看到起点,容易把同一块陆地数两次。一发现陆地就把它涂掉,再用栈记下尚未检查四邻的格子。

两行分别为 110 和 001。第一行左边两格连在一起,右下角虽然斜着碰到它们,题目只算上下左右相连,所以最终有两座岛。

class Solution:
    def numIslands(self, grid):
        rows, cols = len(grid), len(grid[0])
        islands = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] != '1':
                    continue
                islands += 1
                grid[r][c] = '0'
                stack = [(r, c)]
                while stack:
                    x, y = stack.pop()
                    for a, b in ((x-1,y), (x+1,y), (x,y-1), (x,y+1)):
                        if 0 <= a < rows and 0 <= b < cols and grid[a][b] == '1':
                            grid[a][b] = '0'
                            stack.append((a,b))
        return islands

时间 O(mn),栈在最坏情况下占 O(mn) 空间。LeetCode 输入里陆地是字符串 "1"。这份代码会涂改原网格,如果调用方还要用原图,可以先复制每一行。

去力扣做第 200 题

返回 LeetCode 题单 →