Here is the complete implementation:
function islandPerimeter(grid):
rows = grid.rows
cols = grid.cols
perimeter = 0
for r from 0 to rows - 1:
for c from 0 to cols - 1:
if grid[r][c] == 1:
perimeter = perimeter + 4
if r > 0 and grid[r - 1][c] == 1:
perimeter = perimeter - 2
if c > 0 and grid[r][c - 1] == 1:
perimeter = perimeter - 2
return perimeter
Each land cell contributes edges. For each adjacent land cell (above or left), subtract (one edge from each). No DFS needed.
This runs in time and uses space.