You get a rectangular grid of 0s and 1s: 1 is a square of land with side 1, and 0 is water. Squares join only through their sides, not their corners. The grid holds exactly one island, a single connected group of land squares, and everything beyond the grid is water.
The island has no lakes: no water inside it is cut off from the water around it. Return the length of the island’s coastline, its perimeter.
Example 1
Input: grid = [[1, 1, 0],
[0, 1, 1],
[0, 1, 0]]
Output: 12
Why: 5 land cells give 20 sides; 4 shared edges hide 8 of them2 more examples and the constraints
Example 2
Input: grid = [[0, 1],
[0, 1]]
Output: 6
Why: two stacked squares form a 1 by 2 rectangleExample 3
Input: grid = [[1, 1, 1]] Output: 8 Why: a 3 by 1 strip: 3 + 1 + 3 + 1
Constraints
- 1 ≤ rows, columns ≤ 100
- Every cell holds 0 or 1
- The land forms a single island with no lakes
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check all four sides of every land cellO(r·c)
- Count land cells and shared edgesO(r·c)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 100 × 100 grid | Verdict |
|---|---|---|---|
| Check all four sides of every land cell | O(r·c) | Passes; four checks per cell | |
| Count land cells and shared edges | O(r·c) | Best; two checks per cell |
r = rows, c = columns. Both read every cell once; the second does half the neighbour checks.
Edge cases to test
- One land cell. [[1]] has perimeter 4.
- Land on the border. Sides along the grid edge count as coast, like sides facing water.
- Solid block. A full 100 × 100 grid of land has perimeter 400.
- A winding island. A snake-shaped island has a long coast; the counting does not care about its shape.
Common mistakes
- Counting each shared edge twice and subtracting 2 for both, which hides 4 sides per edge instead of 2.
- Reading a neighbour before checking it is inside the grid.
- Running a full DFS from the island, which works but adds a visited set and recursion for no gain.
How to talk through it
- 1Clarify. Exactly one island? No lakes? Do sides on the grid border count?
- 2Find the unit. The perimeter is a count of cell sides that face water or the edge.
- 3Give the formula. Four sides per land cell, minus two per pair of touching land cells.
- 4Code the scan. Look only up and left so each shared edge is counted once.
- 5Test out loud. Run one cell, a straight strip and a 2 × 2 block.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?