Program to find the perimeter of an island shape in Python

Finding the perimeter of an island shape in a binary matrix involves counting the exposed edges of all connected 1s. Each cell with value 1 contributes to the perimeter based on how many of its four sides are exposed (not adjacent to another 1).

Problem Understanding

Given a binary matrix where 0 represents empty cells and 1 represents land blocks, we need to calculate the total perimeter. Each land block initially has 4 sides, but we subtract 1 for each adjacent land block.

For the input matrix:

0 0 0 0 0
0 0 1 1 1
0 0 1 1 0
0 1 1 1 0
0 0 0 0 0

The output will be 14.

Algorithm Approach

For each cell containing 1:

  • Start with 4 sides (perimeter contribution)
  • Check all four adjacent cells (up, down, left, right)
  • Subtract 1 for each adjacent cell that also contains 1
  • Add the remaining sides to the total perimeter

Implementation

class Solution:
    def solve(self, matrix):
        if not matrix or not matrix[0]:
            return 0
        
        rows = len(matrix)
        cols = len(matrix[0])
        perimeter = 0
        
        for row in range(rows):
            for col in range(cols):
                if matrix[row][col] == 1:
                    # Each land cell starts with 4 sides
                    sides = 4
                    
                    # Check right neighbor
                    if col < cols - 1 and matrix[row][col + 1] == 1:
                        sides -= 1
                    
                    # Check left neighbor
                    if col > 0 and matrix[row][col - 1] == 1:
                        sides -= 1
                    
                    # Check bottom neighbor
                    if row < rows - 1 and matrix[row + 1][col] == 1:
                        sides -= 1
                    
                    # Check top neighbor
                    if row > 0 and matrix[row - 1][col] == 1:
                        sides -= 1
                    
                    perimeter += sides
        
        return perimeter

# Test the solution
ob = Solution()
matrix = [
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0]
]

print("Matrix:")
for row in matrix:
    print(row)

print(f"\nPerimeter: {ob.solve(matrix)}")
Matrix:
[0, 0, 0, 0, 0]
[0, 0, 1, 1, 1]
[0, 0, 1, 1, 0]
[0, 1, 1, 1, 0]
[0, 0, 0, 0, 0]

Perimeter: 14

Alternative Approach Using Directions

We can make the code more readable by using direction vectors:

def island_perimeter(matrix):
    if not matrix or not matrix[0]:
        return 0
    
    rows, cols = len(matrix), len(matrix[0])
    perimeter = 0
    
    # Direction vectors: up, down, left, right
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    
    for row in range(rows):
        for col in range(cols):
            if matrix[row][col] == 1:
                sides = 4
                
                # Check all four directions
                for dr, dc in directions:
                    new_row, new_col = row + dr, col + dc
                    
                    # If neighbor is within bounds and is land
                    if (0 <= new_row < rows and 
                        0 <= new_col < cols and 
                        matrix[new_row][new_col] == 1):
                        sides -= 1
                
                perimeter += sides
    
    return perimeter

# Test with the same matrix
matrix = [
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0]
]

print(f"Perimeter: {island_perimeter(matrix)}")
Perimeter: 14

How It Works

The algorithm works by examining each land cell and counting its exposed edges. For the example matrix:

  • Cell (1,2): 3 exposed sides (top, left, bottom)
  • Cell (1,3): 2 exposed sides (top, bottom)
  • Cell (1,4): 3 exposed sides (top, right, bottom)
  • And so on for all land cells...

Time and Space Complexity

Time Complexity: O(rows × cols) − we visit each cell once
Space Complexity: O(1) − only using constant extra space

Conclusion

The island perimeter problem is solved by counting exposed edges of each land cell. For each cell with value 1, we start with 4 sides and subtract 1 for each adjacent land cell. This approach efficiently calculates the total perimeter in linear time.

Updated on: 2026-03-25T11:12:37+05:30

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements