Graph Theory37 sections · 1633 units
Open in Course

LeetCode 463 Island Perimeter - Algorithm

Count, do not traverse

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 44 edges. Check each neighbor. If a neighbor is land, subtract 11. Add remaining edges to total.

Time: O(rows×cols)O(rows \times cols). Space: O(1)O(1). No recursion, no visited array, no queue.