The solution is a single nested loop:
function islandPerimeter(grid):
perimeter = 0
rows = grid.rows
cols = grid.cols
for r from 0 to rows - 1:
for c from 0 to cols - 1:
if grid[r][c] == 1:
edges = 4
if r > 0 and grid[r - 1][c] == 1:
edges = edges - 1
if r < rows - 1 and grid[r + 1][c] == 1:
edges = edges - 1
if c > 0 and grid[r][c - 1] == 1:
edges = edges - 1
if c < cols - 1 and grid[r][c + 1] == 1:
edges = edges - 1
perimeter = perimeter + edges
return perimeter
For each land cell, start with edges. Check each neighbor. If a neighbor is land, subtract . Add remaining edges to total.
Time: . Space: . No recursion, no visited array, no queue.