Island Perimeter
这是我第一次参加 LeetCode (力扣) 的每月挑战题组,希望留下点笔记,大家可以参考和互相讨论。😃
第七天问:
现在给你一个二维网格地图,里面每个1
代表土地,0
代表水面。每一个格子都只能是橫向或者竖向相连 (不会斜向相连),而且这个地图上只有一个陸地。
已知:
- 陸地不会有「河流」,意思是「水」(数字
0
) 只能在陸地上下左右存在,不会在陸地之间相连; - 每个格子的四条边界都是 1 ;
- 这个地图网格是一个长方形,长度和宽度都不多于 100。
请写一个程序来求这网格的边长。
题目例子 (引用自LeetCode):
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
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
解题思路:
我想到一个比较简单的方法 (今天时间不多,只想到一个),就是一个一个格子1
逐个看,用 if-clause 查它的上下左右有沒有格子,如果沒有就在总参数 (perimeter
) 加一。但是,坏处是因为需要一个个的看,所以时间需求挺大的。
代码一 (时间复杂度:O(n2))
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
if grid == [[1]]:
return 4
perimeter = 0
for row in range(len(grid)):
for coln in range(len(grid[row])):
if grid[row][coln] == 0:
continue
if row == 0 or grid[row -1][coln] == 0:
perimeter += 1
if coln == 0 or grid[row][coln - 1] == 0:
perimeter += 1
if row == len(grid) - 1 or grid[row + 1][coln] == 0:
perimeter += 1
if coln == len(grid[row]) - 1 or grid[row][coln + 1] == 0:
perimeter += 1
return perimeter