Island Perimeter Problem
Description
LeetCode Problem 463.
You are given row x col grid representing a map where grid[i][j] = 1 representsland 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.
Example 1:
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input: grid = [[1]]
Output: 4
Example 3:
Input: grid = [[1,0]]
Output: 4
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
Approach: Count Cells and Shared Edges
The perimeter is made of the edges of land cells that do not touch another land cell. No search over the island is needed; one pass over the grid is enough.
Every land cell brings 4 edges. Wherever two land cells are side by side, the edge between them is inside the island, and it removes one edge from each of the two cells. So:
perimeter = 4 · (land cells) − 2 · (pairs of adjacent land cells)
To count each adjacent pair exactly once, look only at the cell's neighbor above and the neighbor to the left. The pair with the cell below or to the right is counted later, when the scan reaches that cell. Checking all four neighbors and still subtracting 2 would count every shared edge twice.
For Example 1 there are 7 land cells and 6 adjacent pairs, so the perimeter is 4 · 7 − 2 · 6 = 16.
The edges along the grid border need no special case: a cell in row 0 has no neighbor above, so nothing is subtracted for it, and its top edge stays in the count.
Complexity: O(rows · cols) time and O(1) extra space.
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
perimeter = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 0:
continue
perimeter += 4 # a lone land cell has 4 edges
# Each shared edge with a land neighbor hides one edge of each cell.
# Checking only up and left counts every shared edge once.
if r > 0 and grid[r - 1][c] == 1:
perimeter -= 2
if c > 0 and grid[r][c - 1] == 1:
perimeter -= 2
return perimeter