15% off all plans & roadmaps Use code
See plansProblem editorial
You are given a rectangular binary grid in grid. Each cell with value 1 is land, and each cell with value 0 is water. Cells are neighbors only when they share an edge; diagonal contact does not count. All land cells together form one island, meaning one edge-connected group of land cells.
Island Perimeter is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph DFS - Connected Components / Island Counting subpattern. The pattern covers dFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
The reference solution runs in O(R * C), where R is the number of rows and C is the number of columns. time and O(1) auxiliary space. space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Island Perimeter is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph DFS - Connected Components / Island Counting subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.