All challenges
Medium 0 solved 0% acceptance

Island Perimeter

Measure the coastline of land cells in a grid.

Problem

The grid holds 1 for land and 0 for water. Each land cell is a 1×1 square. Compute the total perimeter of all land: every side of a land cell that faces water or the grid edge counts 1.

Implement island_perimeter(grid).

Input

grid: A rectangular grid of 0s and 1s.

Output

Return the total perimeter.

Constraints

0 ≤ rows, columns ≤ 200

Examples

Example 1
Input:
grid = [
    [0, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 1, 0, 0],
    [1, 1, 0, 0]
]

Expected output:
expected = 16
Input:
std::vector<std::vector<long long>> grid = {
    {0, 1, 0, 0},
    {1, 1, 1, 0},
    {0, 1, 0, 0},
    {1, 1, 0, 0}
};

Expected output:
long long expected = 16;
Input:
long[][] grid = new long[][] {
    new long[] {0, 1, 0, 0},
    new long[] {1, 1, 1, 0},
    new long[] {0, 1, 0, 0},
    new long[] {1, 1, 0, 0}
};

Expected output:
long expected = 16;

Explanation

7 land cells have 28 sides; 6 shared edges remove 12: perimeter 16.

Example 2
Input:
grid = [
    [1]
]

Expected output:
expected = 4
Input:
std::vector<std::vector<long long>> grid = {
    {1}
};

Expected output:
long long expected = 4;
Input:
long[][] grid = new long[][] {
    new long[] {1}
};

Expected output:
long expected = 4;

Explanation

A single land cell has 4 sides.

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.