Island Perimeter
Real-world version: Edge Trim for the Solar ArrayThe statement here is our own: the same inputs, outputs and technique.
A flat roof is drawn as grid, a rectangle of one-metre squares. grid[i][j] is 1 when a solar panel sits on that square and 0 when the square is bare.
The panels form exactly one array: every panel square can be reached from every other by stepping between squares that share a full edge, never through a corner. An installer runs weatherproof trim along every panel edge that is not shared with another panel, including edges that fall on the outer boundary of the drawing.
Return the total length of trim in metres.
Examples
Example 1
- Input
- grid = [[0, 1, 1, 0], [0, 1, 0, 0], [1, 1, 1, 0]]
- Output
- 14
Going square by square and counting the edges that face a bare square or the outside of the drawing: 2 at row 0 column 1, 3 at row 0 column 2, 2 at row 1 column 1, 3 at row 2 column 0, 1 at row 2 column 1 and 3 at row 2 column 2. Those come to 14 metres.
Example 2
- Input
- grid = [[1, 0, 1], [1, 0, 1], [1, 1, 1]]
- Output
- 16
The two top corners each expose 3 edges and the other five squares expose 2 each, which comes to 16 metres. The bare notch at row 0 column 1 and row 1 column 1 is trimmed on both of its sides.
Example 3
- Input
- grid = [[1, 1], [1, 1]]
- Output
- 8
Each of the four squares has two edges facing the outside of the drawing and two facing another panel, so the trim runs 2 metres per square, 8 in total.
Constraints
- rows == grid.length
- cols == grid[i].length
- 1 <= rows, cols <= 100
- grid[i][j] is 0 or 1.
- grid holds exactly one panel array, and it holds at least one panel square.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def island_perimeter(grid: list[list[int]]) -> int:public int islandPerimeter(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's