All problems
0543EasyArrayDepth-First SearchBreadth-First SearchMatrix

Edge Trim for the Solar Array

Tracked in this browser only
Write code

Trains the technique from

LeetCode 463Island Perimeter

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def island_perimeter(grid: list[list[int]]) -> int:
Java
public int islandPerimeter(int[][] grid)
September 7
Apply