LeetCode 题解工作台

岛屿数量

给你一个由 '1' (陆地)和 '0' (水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 此外,你可以假设该网格的四条边均被水包围。 示例 1: 输入: grid = [ ['1','1','1','1','0'],…

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 图·搜索

bolt

答案摘要

我们可以使用深度优先搜索(DFS)来遍历每个岛屿。遍历网格中的每个单元格 $(i, j)$,如果该单元格的值为 '1',则说明我们找到了一个新的岛屿。我们可以从该单元格开始进行 DFS,将与之相连的所有陆地单元格的值都标记为 '0',以避免重复计数。每次找到一个新的岛屿时,我们将岛屿数量加 1。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 和 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

 

示例 1:

输入:grid = [
  ['1','1','1','1','0'],
  ['1','1','0','1','0'],
  ['1','1','0','0','0'],
  ['0','0','0','0','0']
]
输出:1

示例 2:

输入:grid = [
  ['1','1','0','0','0'],
  ['1','1','0','0','0'],
  ['0','0','1','0','0'],
  ['0','0','0','1','1']
]
输出:3

 

提示:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] 的值为 '0''1'
lightbulb

解题思路

方法一:DFS

我们可以使用深度优先搜索(DFS)来遍历每个岛屿。遍历网格中的每个单元格 (i,j)(i, j),如果该单元格的值为 '1',则说明我们找到了一个新的岛屿。我们可以从该单元格开始进行 DFS,将与之相连的所有陆地单元格的值都标记为 '0',以避免重复计数。每次找到一个新的岛屿时,我们将岛屿数量加 1。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别为网格的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def dfs(i, j):
            grid[i][j] = '0'
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':
                    dfs(x, y)

        ans = 0
        dirs = (-1, 0, 1, 0, -1)
        m, n = len(grid), len(grid[0])
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    dfs(i, j)
                    ans += 1
        return ans
speed

复杂度分析

指标
时间complexity varies: DFS/BFS is O(m _n) as each cell is visited once. Union-Find is O(m_ n * α(m _n)) where α is the inverse Ackermann function. Space complexity is O(m_ n) for visited markers or recursion/queue storage depending on the approach.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect array traversal plus DFS/BFS as a primary approach.

  • question_mark

    Check if candidate handles edge cases like all water or single-cell islands.

  • question_mark

    Look for marking strategies to prevent revisiting cells and miscounting islands.

warning

常见陷阱

外企场景
  • error

    Failing to mark visited cells, causing infinite loops or double-counting.

  • error

    Confusing diagonal adjacency with vertical/horizontal adjacency.

  • error

    Using recursion without stack limits, which may cause stack overflow on large grids.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count islands considering diagonal adjacency as connected.

  • arrow_right_alt

    Return the size of the largest island instead of the count.

  • arrow_right_alt

    Allow dynamic addition of land cells and update the island count incrementally.

help

常见问题

外企场景

岛屿数量题解:图·搜索 | LeetCode #200 中等