Skip to content

Instantly share code, notes, and snippets.

@frectonz
Last active October 27, 2023 12:43
Show Gist options
  • Save frectonz/11c0c52855ed81a59a8f6ce77daa5d3f to your computer and use it in GitHub Desktop.
Save frectonz/11c0c52855ed81a59a8f6ce77daa5d3f to your computer and use it in GitHub Desktop.
def island_perimeter(grid):
perimeter = 0
for i in range(len(grid)):
row = grid[i]
for j in range(len(row)):
cell = grid[i][j]
if cell != 1:
continue
top = grid[i - 1][j] if i != 0 else 0
bottom = grid[i + 1][j] if i != len(grid) - 1 else 0
left = grid[i][j - 1] if j != 0 else 0
right = grid[i][j + 1] if j != len(row) - 1 else 0
for other in [top, bottom, left, right]:
if other == 0:
perimeter += 1
return perimeter
grid1 = [
[0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0]
]
assert 12 == island_perimeter(grid1)
grid2 = [
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]
]
assert 16 == island_perimeter(grid2)
grid3 = [
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1]
]
assert 20 == island_perimeter(grid3)
grid4 = [
[0, 1, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 1],
[0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0]
]
assert 28 == island_perimeter(grid4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment