-
Notifications
You must be signed in to change notification settings - Fork 0
/
5-island_perimeter.py
28 lines (24 loc) · 950 Bytes
/
5-island_perimeter.py
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
#!/usr/bin/python3
"""Answer to one of the interview Questions
A module for working with grid structures.
"""
def island_perimeter(grid: list) -> int:
"""Computes the perimeter of the island described in the grid.
Args:
grid (list of list of integers): For each integer, 0 represents
water and 1 represents land.
Returns:
int: the perimeter of the island.
"""
perimeter = 0
rows = len(grid)
for i in range(rows):
cols = len(grid[i])
for j in range(cols):
if (grid[i][j] == 1):
left = 1 if j == 0 or grid[i][j - 1] == 0 else 0
top = 1 if i == 0 or grid[i - 1][j] == 0 else 0
right = 1 if j == cols - 1 or grid[i][j + 1] == 0 else 0
bottom = 1 if i == rows - 1 or grid[i + 1][j] == 0 else 0
perimeter += (top + right + bottom + left)
return perimeter