You are given a map in form of a two-dimensional integer grid where 1 represents land and 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” (water inside that 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.
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16
How to count
- Each island are supposed to have 4 sides.
- An island that has neighbor on the right will lose 2 sides
- An island that has neighbor on the bottom will lose 2 sides
- Initialize an island counter and a side counter
- Loop through each row
- Loop through each item in that row
- If it’s 1, increase the island counter by 1
- Check if it has right neighbor, if so increase the neighbor counter by 1
- Check if it has bottom neighbor, if so increase the neighbor counter by 1
- After all items are checked, return the total count using this formula
islands * 4 - neighbor * 2