> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/suan-fa/dfs/463-dao-yu-de-zhou-chang.md).

# \[463]\[简单]\[DFS] 岛屿的周长

## 题目描述

[463. 岛屿的周长](https://leetcode-cn.com/problems/island-perimeter/)

给定一个包含 0 和 1 的二维网格地图，其中 1 表示陆地 0 表示水域。

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

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

示例 :

```
输入:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

输出: 16

解释: 它的周长是下面图片中的 16 个黄色的边：
```

![](/files/-MI7NtS8MMTiLmeUajGt)

## 解题思路

### 思路一

找到某一块陆地时, 我们想象成将陆地扩展到这个位置, 而根据这个位置周围已探索的陆地, 将会对整体的周长产生不同的影响:

* 0: 周围没有土地被探索过, 周长+4
* 1: 周围有1块土地被探索过, 周长+2
* 2: 周围有2块土地被探索过, 周长+0
* 3: 周围有3块土地被探索过, 周长-2
* 4: 周围有4块土地被探索过, 周长-4

```python
class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        n = len(grid)
        if n == 0:
            return 0
        m = len(grid[0])

        count = 0

        def dfs(i, j):
            if not 0 <= i < n or not 0 <= j < m:
                return
            if grid[i][j] == 0 or grid[i][j] == 2:
                return

            grid[i][j] = 2
            neighbors = 0
            neighbors += 1 if i - 1 >= 0 and grid[i - 1][j] == 2 else 0
            neighbors += 1 if i + 1 < n and grid[i + 1][j] == 2 else 0
            neighbors += 1 if j - 1 >= 0 and grid[i][j - 1] == 2 else 0
            neighbors += 1 if j + 1 < m and grid[i][j + 1] == 2 else 0
            nonlocal count
            count += (4 - neighbors * 2)

            dfs(i - 1, j)
            dfs(i + 1, j)
            dfs(i, j - 1)
            dfs(i, j + 1)

        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    dfs(i, j)
                    return count
        return count
```

### 思路二

参考: [岛屿类问题的通用解法、DFS 遍历框架](https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-lei-wen-ti-de-tong-yong-jie-fa-dfs-bian-li-/)
