You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Example:

1
2
3
4
5
6
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Answer: 16

思路

题目的意思是需要我们找到矩阵当中组成“岛屿”的周长。不难看出,岛屿的周长与岛屿的面积、岛屿孤立的格数有关。可以通过 result = island 4 - neighbour 2 来计算最终结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
count = 0
col = len(grid)
row = len(grid[0])
for i in range(col):
for j in range(row):
if (grid[i][j] == 1):
#如果这个点是岛屿的一部分
#对岛屿的周长情况进行判断
if (i == 0):
count = count + 1
else:
#如果这个点左边不再是岛屿
if(grid[i-1][j] == 0):
count = count + 1
if (i == (col-1)):
count = count + 1
else:
#如果这个点右边不再是岛屿
if(grid[i+1][j] == 0):
count = count + 1
if (j == 0):
count = count + 1
else:
if(grid[i][j-1] == 0):
count = count + 1
if (j == (row-1)):
count = count + 1
else:
if(grid[i][j+1] == 0):
count = count + 1
return count