◀ THE GRIND — GRAPHS

Island Perimeter

The drill: A single island sits in a 0/1 grid — count the total length of its coastline, where every land edge touching water or the grid's border adds one unit of perimeter.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A rectangular grid holds a single connected mass of land marked 1, surrounded by water marked 0. The job is to measure the total length of coastline that mass produces — every unit edge where land meets water or the outer edge of the map.

Land only connects orthogonally, so two 1s touching corner-to-corner are not part of the same coastline calculation — each of the four sides of every land cell either borders more land, water, or nothing at all, and only the last two kinds of edges count.

The island arrives as one single connected shape with no lake carved out of its middle, so nothing needs merging or splitting — the whole grid can be walked once, tallying exposed edges as they're found.

EX 01
grid = [[1]]
4
SINGLE LAND CELL
EX 02
grid = [[1, 1]]
6
1X2 STRIP
EX 03
grid = [[1, 1], [1, 1]]
8
2X2 SQUARE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every land cell contributes some perimeter, but a shared edge between two land cells contributes nothing — the coastline only grows where land meets water or the map's edge.

HINT 2 THE STRUCTURE

Walk each land cell and look in all four directions: any neighbour that's water, or off the grid entirely, is one unit of coastline. Land neighbours are the ones you don't count.

HINT 3 ONE STEP FROM THE ANSWER

Because every interior land-land edge is shared by exactly two cells, you can also get there by counting: 4 × (land cells) − 2 × (adjacent land pairs), checking only the right and down neighbour of each cell to avoid double-counting a pair.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE SHARED-EDGE COUNTPATTERN · SHARED EDGES SUBTRACTEDT-shaped island, 3×4 grid
0
1
0
0
1
1
1
0
0
1
0
0
STEP 1

Perimeter = 4×(land cells) − 2×(right/down land-land adjacencies). Scan every land cell once.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/island-perimeter.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        land = 0
        adjacent = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    land += 1
                    if r + 1 < rows and grid[r + 1][c] == 1:
                        adjacent += 1
                    if c + 1 < cols and grid[r][c + 1] == 1:
                        adjacent += 1
        return 4 * land - 2 * adjacent
TIME O(ROWS·COLS)SPACE O(1)PYTHON · RACE PACE · 14 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED