Perimeter of Every Island
Problem statement
Given a rectangular binary matrix grid, return the perimeter of every island. A cell containing 1 is a unit-square land cell; 0 is water.
An island is a maximal group of land cells connected horizontally or vertically through shared edges. Diagonal contact does not connect islands.
An island’s perimeter is the number of unit edges next to water or outside the grid. Edges around enclosed water holes also count; edges shared by two land cells do not.
Return one integer per island in row-major discovery order: scan rows from top to bottom and columns from left to right, and append an island’s perimeter when its first land cell is encountered. Keep separate entries for islands with equal perimeters.
If the grid has no rows, no columns or no land cells, return an empty array.
What the interview report shared
- The initial island-summary request included coordinates, each island’s area and perimeter.
- The interviewer reduced the requested implementation to perimeter calculation.
- The candidate had to run the code successfully and debugged it with the interviewer.
Function
islandPerimeters(grid: int[][]) → int[]Examples
Example 1
grid = [[1,1,0,0,1],[1,0,0,0,1],[0,0,1,1,0],[1,0,0,1,0]]return = [8,6,8,4]The islands first appear at (0,0), (0,4), (2,2) and (3,0). Their perimeters are 8, 6, 8 and 4; equal perimeters remain separate results.
Example 2
grid = [[1,1,1],[1,0,1],[1,1,1]]return = [16]The eight land cells form one island. Its outer boundary has length 12 and the central water hole adds 4, for a perimeter of 16.
Example 3
grid = []return = []There are no cells and no islands, so the result is an empty array.
Constraints
0 <= grid.length <= 32.- Every row has the same length, between
0and32inclusive. - Every cell is
0or1. - Only horizontal and vertical shared edges connect land cells.
- Inputs satisfy these rules; ragged rows and other cell values are outside the accepted domain.