Categories:

Tags:



Problem

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.

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.

Solution

The problem Island Perimeter can be solved using the technique from Number of Segments in a String. When we consider a horizontal perimeter for a row, it is obvious that consecutive lands have a horizontal perimeter of 2 no matter its size. If there are disjointed parts of the island on the same row, new horizontal perimeter of 2 are added for each segments. Therefore, horizontal perimeter can be calculated by finding the number of segments for all rows and vertical perimeter by the number of segments on all columns.

Implementation

class Solution
{
  public:
    int islandPerimeter(vector<vector<int>> &grid)
    {
        int ret = 0;
        for (int i = 0; i < grid.size(); i++)
            for (int j = 0; j < grid[i].size(); j++)
                if (grid[i][j] == 1)
                {
                    if (j == 0 || grid[i][j - 1] == 0)
                        ret += 2;
                    if (i == 0 || grid[i - 1][j] == 0)
                        ret += 2;
                }

        return ret;
    }
};