# Leetcode 463. Island Perimeter 題解
## 逐一計算
```python=
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
xc,yc = len(grid[0]), len(grid)
output = 0
for y in range(yc):
for x in range(xc):
if grid[y][x] == 1:
borders = 4
if x >= 1:
if grid[y][x-1] == 1: # 左
borders -= 1
if x + 1 < xc:
if grid[y][x+1] == 1: # 右
borders -= 1
if y >= 1:
if grid[y-1][x] == 1: # 上
borders -= 1
if y + 1 < yc:
if grid[y+1][x] == 1: # 下
borders -= 1
output += borders
return output
```
## 計算右下相鄰島

```python=
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
xc, yc = len(grid[0]), len(grid)
islands, neighbours = 0, 0
for y in range(yc):
for x in range(xc):
if grid[y][x] == 1:
islands += 1
if x + 1 < xc:
if grid[y][x + 1] == 1: # 右
neighbours += 1
if y + 1 < yc:
if grid[y + 1][x] == 1: # 下
neighbours += 1
return islands * 4 - neighbours * 2
```
### 2024.04.18 每日
```python=
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m,n = len(grid), len(grid[0])
dem = [[0,-1], [0,1], [-1,0], [1,0]]
perimeters = 0
for y in range(m):
for x in range(n):
perimeters += grid[y][x] * 4
if grid[y][x] == 1:
for dx,dy in dem:
dx = x + dx
dy = y + dy
if 0 <= dx < n and 0 <= dy < m:
perimeters -= grid[dy][dx]
return perimeters
```