Island Perimeter
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.

第一种方法,我们使用并列的if,对于每个格子的四条边分别来处理,首先看左边的边,只有当左边的边处于第一个位置或者当前格子的左面没有岛格子的时候,左边的边计入周长。其他三条边的分析情况都跟左边的边相似。
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid) #rows
m = len(grid[0]) #columns
result = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
continue
if j == 0 or grid[i][j-1] == 0:
result += 1
if i == 0 or grid[i-1][j] == 0:
result += 1
if j == m-1 or grid[i][j+1] == 0:
result += 1
if i == n-1 or grid [i+1][j] == 0:
result += 1
return result
第二种方法 每个格子周长为4,两个格子相邻时周长-2。
也就是说对于每个岛屿格子先默认加上四条边,然后检查其左面和上面是否有岛屿格子,有的话分别减去两条边,这样也能得到正确的结果
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
m = len(grid[0]) if n else 0 #这样写通用的原因是, 当matrix = [], row = 0, col =0
result = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
result += 4
if grid[i-1][j] == 1 and i > 0:
result -= 2
if grid[i][j-1] == 1 and j > 0:
result -= 2
return result
复习:
continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C.
Last updated
Was this helpful?