Graph Theory37 sections · 1633 units
Open in Course

LeetCode 463 Island Perimeter - Implementation

Edge counting code

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 44 edges. For each adjacent land cell (above or left), subtract 22 (one edge from each). No DFS needed.

This runs in O(m×n)O(m \times n) time and uses O(1)O(1) space.