You are given a 2D matrix (m x n) of 1s and 0s where 1 represents land and 0 represents water.
Grid cells are connected horizontally orvertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
An island is a group is cells connected horizontally or vertically, but not diagonally. There is guaranteed to be exactly one island in this grid, and the island doesn't have water inside that isn't connected to the water around the island. Each cell has a side length of 1.
Determine the perimeter of this island.
This is my solution
def island_perimeter(grid):
rows = len(grid)
cols = len(grid[0])
perimeter = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
perimeter += 4 # start with the assumption that all sides are perimeter
# Check adjacent cells
if row > 0 and grid[row - 1][col] == 1:
perimeter -= 2 # deduct 2 if the current cell has a neighbor above
if col > 0 and grid[row][col - 1] == 1:
perimeter -= 2 # deduct 2 if the current cell has a neighbor to the left
return perimeter
Can anyone add this question on LeetCode. Also provide their own solution