Island Perimeter

You are given a `row x col` grid where `grid[i][j] = 1` is land and `grid[i][j] = 0` is water. Cells connect only horizontally and vertically. The grid holds exactly one island, is surrounded by water, and the island has no lakes (no water trapped inside it). Each cell is a square with side length 1. Return the perimeter of the island.

30:00

Island Perimeter
easy
Free written solution
Topics
Companies

You are given a row x col grid where grid[i][j] = 1 is land and grid[i][j] = 0 is water. Cells connect only horizontally and vertically. The grid holds exactly one island, is surrounded by water, and the island has no lakes (no water trapped inside it). Each cell is a square with side length 1. Return the perimeter of the island.

Example 1:
Input: {"grid":[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]}
Output: 16
Constraints:
  • row==grid.length\text{row} == \text{grid.length}

  • col==grid[i].length\text{col} == \text{grid}[i].\text{length}

  • 1≤row,col≤1001 \leq \text{row}, \text{col} \leq 100

  • grid[i][j]\text{grid}[i][j] is 00 or 11

  • There is exactly one island in grid.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]}

perimeter starts at 0. Each land cell brings a fence of 4 sides, and every side shared with another land cell must come off.

gold = fence counted in the perimeter, red dashes = shared edge just removed

perimeter

0

4 x land - 2 x shared edges

4 x 0 - 2 x 0 = 0

Variables
VariableValue
perimeter0
DepthFunction Call
Stack empty
0/14