We have seen countless other problems where we are given a grid and are required to traverse an island. But this is not as complex as a DFS in a matrix. The trick to an efficient algorithm for this problem is understanding how we can get the running perimeter of the entire island as we traverse.
We are told that there is only one island as such - this means we do not have to worry about keeping track if an island stops and a new one begins.
The perimeter is the sum of lengths of outer sides. We are confident that an island consists of 1s and water consists of 0s. While traversing for each cell, if we keep track of how many 1s and 0s it has as its neighbors - we are good to go.
Since a cell would have four sides (we assume this is a square matrix and each cell has four sides), subtract the number of 1s (inner boundaries) from 4 to get outer boundaries.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is
O(N * M)
whereN = len(grid)
andM = len(grid[i])
. -
Memory
The memory usage is
O(N)
where N is the hashmap size.
— A