LeetCode 题解工作台

岛屿的周长

给定一个 row x col 的二维网格地图 grid ,其中: grid[i][j] = 1 表示陆地, grid[i][j] = 0 表示水域。 网格中的格子 水平和垂直 方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 图·搜索

bolt

答案摘要

class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 row x col 的二维网格地图 grid ,其中:grid[i][j] = 1 表示陆地, grid[i][j] = 0 表示水域。

网格中的格子 水平和垂直 方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。

岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。

 

示例 1:

输入:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
输出:16
解释:它的周长是上面图片中的 16 个黄色的边

示例 2:

输入:grid = [[1]]
输出:4

示例 3:

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

 

提示:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j]01
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    ans += 4
                    if i < m - 1 and grid[i + 1][j] == 1:
                        ans -= 2
                    if j < n - 1 and grid[i][j + 1] == 1:
                        ans -= 2
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate’s ability to efficiently implement DFS or BFS on a grid.

  • question_mark

    Pay attention to their handling of boundary conditions and grid traversal.

  • question_mark

    Check for optimizations, such as early termination or pruning in the search algorithms.

warning

常见陷阱

外企场景
  • error

    Not handling grid boundaries correctly, which might cause index errors or incorrect perimeter calculation.

  • error

    Failing to account for the fact that only water cells or boundaries contribute to the perimeter.

  • error

    Misunderstanding the concept of a single island, leading to incorrect grid exploration.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the grid contains multiple disconnected islands? (The problem specifies exactly one island.)

  • arrow_right_alt

    How would the solution change if the grid had diagonal connectivity?

  • arrow_right_alt

    Can this problem be solved in O(1) space?

help

常见问题

外企场景

岛屿的周长题解:图·搜索 | LeetCode #463 简单