Search⌘ K
AI Features

Find Perimeter of Island

Understand how to calculate the perimeter of an island on a grid by analyzing land and water cells. Learn an optimized method that reduces redundant checks by inspecting only left and upper neighbors. This lesson helps you develop skills in grid traversal and problem-solving with time and space complexity considerations.

Statement

Given a grid representing a map where: :

  • grid[i][j] = 1 represents land
  • grid[i][j] = 0 represents water

Each cell is a square with length = 1 and the grid is rectangular.

Find the perimeter of the island.

Constraints

  • The length and width of the grid cannot exceed 100.
  • Grid cells are connected only horizontally or vertically.
  • There is exactly one island, and the grid is completely surrounded by water.
  • The island does not have lakes. The water inside is not connected to the water around the island.

Example

Sample input

[[0,1,0,0,0], [1,1,1,1,0], [0,0,1,0,0], [1,1,1,1,1],[0,0,1,0,1]]

Here’s a sample grid. The blue cells represent water and yellow cells represent land:

g array

Expected output

28

Try it yourself

#include <iostream>
#include <vector>
using namespace std;
int IslandPerimeter(vector<vector<int>> grid) {
// TODO: Write - Your - Code
return -1;
}

Solution

Before we move on to the solution, we must keep in mind that:

  • A land cell with no surrounding cell has a perimeter of
...