[LeetCode] Challenge log 463

463. Island Perimeter

s1: traverse all “1”, add the number of adjacent “0”s to the output. O(n) time.

s2: check every adjacent pairs horizontally and vertically, add 1 to the ouput if the pair is (“0”, “1”). In other words, we are checking every edge to check if it is a border. O(n) time but neater.

useful skill: map(list, zip(*grid)) = transpose(grid).


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

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = 0
nrow = len(grid)
ncol = len(grid[0])
loc = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i in range(nrow):
for j in range(ncol):
if grid[i][j] == 1:
for a, b in loc:
if i + a >= nrow or i + a < 0 or j + b >= ncol or j + b < 0:
res += 1
elif grid[i + a][j + b] == 0:
res += 1
return res
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = 0
res += sum([sum([a != b for a, b in zip(row + [0], [0] + row)]) for row in grid])
grid = map(list, zip(*grid))
res += sum([sum([a != b for a, b in zip(row + [0], [0] + row)]) for row in grid])
return res
0%