Island Perimeter

Updated on 03 June, 2025
Island Perimeter header image

Problem Statement

In this challenge, you are provided with a grid, represented as a 2D array where each cell can be either land (1) or water (0). This grid forms a rectangular map, and each cell is directly connected to its adjacent cells horizontally or vertically but not diagonally. The entire grid is surrounded by water, ensuring there's a clear distinction between the edge of the island and the surrounding water.

Your task is to calculate the perimeter of the island within this grid. An island is defined as a group of connected land cells (1s) and it is guaranteed that there is exactly one such island in the given grid. This island does not contain any enclosed bodies of water ("lakes"). The perimeter is defined by the number of edges facing water or the grid boundary. You are to assume that each cell in the grid is a square with side length 1.

Examples

Example 1

Input:

grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]

Output:

16

Explanation:

The perimeter is the 16 yellow stripes in the image above.

Example 2

Input:

grid = [[1]]

Output:

4

Example 3

Input:

grid = [[1,0]]

Output:

4

Constraints

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] is 0 or 1.
  • There is exactly one island in grid.

Approach and Intuition

To determine the perimeter of the island described in the grid, you can follow these steps:

  1. Traverse each cell of the grid.
  2. For each land cell (1), check its surrounding cells (up, down, left, right).
    • If a surrounding cell is water (0) or it lies outside the boundary of the grid, it contributes 1 to the perimeter.
    • Otherwise, if the adjacent cell is also land (1), it does not add to the perimeter on that side.
  3. Sum up the contributions from all sides of all land cells to get the total perimeter.

This approach checks each land cell's surroundings to account for edges that are adjacent to water or external boundaries, which essentially are boundary lines of the island. Examples provided illustrate how different configurations of the grid affect the calculation of the perimeter:

  • In the first example, the arrangement of the cells creates multiple extensions and indentations, thereby lengthening the perimeter.
  • In the second example, a single land cell on all sides is exposed to water, giving a straightforward perimeter of 4.
  • The third example, similar to the second, has a single land cell alongside a water cell, also resulting in a perimeter of 4.

The constraints ensure that the perimeter calculation remains within computationally feasible limits, avoiding excessively large or complex grid structures. This method efficiently computes the island's perimeter using straightforward checks and accumulations based on the grid's immediate cellular environment.

Solutions

  • Java
  • Python
java
class Solution {
    public int calculateIslandPerimeter(int[][] grid) {
        int row_count = grid.length;
        int col_count = grid[0].length;
        
        int perimeter = 0;
        for (int row = 0; row < row_count; row++) {
            for (int col = 0; col < col_count; col++) {
                if (grid[row][col] == 1) {
                    perimeter += 4;
                    
                    if (row > 0 && grid[row-1][col] == 1) {
                        perimeter -= 2;
                    }
                    
                    if (col > 0 && grid[row][col-1] == 1) {
                        perimeter -= 2;
                    }
                }
            }
        }
        
        return perimeter;
    }
}

The provided Java solution computes the perimeter of an island represented within a 2D grid. Each cell in the grid can either be part of the land (1) or water (0). The solution iteratively checks each cell in the matrix.

  • Whenever a land cell is found, the perimeter is incremented by 4 initially because a single isolated cell has four sides.
  • If the cell directly above the current cell ([row-1][col]) is also land, then they share a border, and two sides are subtracted from the perimeter.
  • Similarly, if the cell to the left of the current cell ([row][col-1]) is land, it implies another shared border, thus reducing the perimeter by an additional two sides.

The algorithm navigates through each row and column of the grid effectively using nested loops. The procedure ensures that each potential land cell is examined for adjacent land cells both above and to the left, adjusting the perimeter accordingly.

The key points from the code:

  1. Initialize the perimeter to 0 before commencing the iteration.
  2. Use nested loops to assess each cell based on its content and its relation to neighboring cells.
  3. Adjust the perimeter count based on the shared borders with adjacent cells.
  4. Return the calculated perimeter at the end of the function.
python
class Solution:
    def calculatePerimeter(self, matrix: List[List[int]]) -> int:
        height = len(matrix)
        width = len(matrix[0])
        
        perimeter = 0
        
        for i in range(height):
            for j in range(width):
                if matrix[i][j] == 1:
                    perimeter += 4
                    
                    if i > 0 and matrix[i-1][j] == 1:
                        perimeter -= 2
                        
                    if j > 0 and matrix[i][j-1] == 1:
                        perimeter -= 2
        
        return perimeter

Title: Island Perimeter

Language: Python 3

Solution Summary:

The provided Python code efficiently calculates the perimeter of an "island" on a grid. An island is represented by 1s on a 2D matrix, with 0s representing water. The code uses a nested loop to traverse each cell of the matrix:

  • If a cell contains a 1, the perimeter is initially increased by 4 (assuming the cell is surrounded by water on all four sides).
  • Adjustments are made if the cell has neighboring 1s:
    • The perimeter is decreased by 2 for each adjacent 1 to the left or above the current cell, reflecting shared borders that do not contribute to the overall perimeter.

By iterating through the matrix and adjusting the perimeter calculation based on neighboring cells, the algorithm accurately accounts for the intricacies of shared borders within the island configurations.

This solution is effective for various matrix sizes and any configuration of islands within the grid.

Comments

No comments yet.