Given a binary matrix in which the values 0 and 1 correspond to land and water, respectively, and the connected ones form exactly one island, find the perimeter of an island.

Assume that there are no lakes on the island, and all the ones that exist are connected only vertically or horizontally, not diagonally. Each cell of the matrix is a square with one unit-long side. For instance, take a look at the illustration below:

  

The above image highlights water in blue and land in gray in a 5 × 4 binary matrix. The island represents the following matrix, and the perimeter of the island is 24, as highlighted above.

island = [
    [0, 1, 1, 1],
    [1, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 1, 0, 0],
    [0, 1, 1, 1]
]

We can find the perimeter of the island simply by counting the number of sides adjacent to the water. The idea is to traverse the matrix and check if the current cell is on land or not. If the current cell is land, increment the perimeter count whenever we encounter a boundary. i.e., its top, bottom, right, or left side is adjacent to the water.

 
Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

24

Java


Download  Run Code

Output:

24

Python


Download  Run Code

Output:

24

The time complexity of the proposed solution is O(M × N), where M and N are dimensions of the matrix, and doesn’t require any extra space.