Island Perimeter

Island Perimeter

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.

Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

LeetCode Problem - 463

class Solution {
    int count; // Variable to keep track of island count (seems unused)

    // Function to calculate the perimeter of the island
    public int islandPerimeter(int[][] grid) {
        int perimeter = 0; // Initialize the perimeter counter
        for(int row=0; row<grid.length; row++){ // Iterate over each row
            for(int column=0; column<grid[row].length; column++){ // Iterate over each column in the row
                if(grid[row][column] == 1) { // If land (1) is found
                    perimeter += 4; // Add 4 to the perimeter (all sides)

                    // Check if adjacent cells are also land
                    if(row > 0 && grid[row-1][column] == 1) perimeter -= 2; // Subtract 2 if upper cell is land
                    if(column > 0 && grid[row][column-1] == 1) perimeter -= 2; // Subtract 2 if left cell is land
                }
            }
        }
        return perimeter; // Return the total perimeter of the island
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!