LeetCode problem: Island Perimeter link>>
Question
You are given a 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.
Return the perimeter of the island.
Example 1:
Input: grid = [
[1,1,0,0],
[1,0,0,0],
[1,1,1,0],
[0,0,1,1]
]
Output: 18
Explanation: The perimeter is the 18 red stripes shown in the image above.
Example 2:
Input: grid = [[1,0]]
Output: 4
Constraints:
row == grid.lengthcol == grid[i].length1 <= row, col <= 100grid[i][j]is0or1.- There is exactly one island in
grid.
Solution
Video Explanation
Prerequisites
Before attempting this problem, you should be comfortable with:
- 2D Array (Grid) Traversal - Iterating through rows and columns of a matrix
- Depth First Search (DFS) - Recursive exploration of connected components in a grid
- Breadth First Search (BFS) - Level-by-level traversal using a queue
1. Depth First Search
Intuition
The perimeter of an island comes from the edges of land cells that touch either water or the grid boundary. Using DFS, we can traverse all connected land cells starting from any land cell. Each time we step outside the grid or hit water, we've found one edge of the perimeter. By recursively exploring in all four directions and counting these boundary crossings, we accumulate the total perimeter.
Algorithm
- Traverse the grid to find the first land cell.
- Start
dfsfrom that cell, marking cells as visited. - For each cell in the
dfs:
-
- If out of bounds or water, return 1 (found a perimeter edge).
- If already visited, return 0.
- Otherwise, mark as visited and recursively call dfs on all four neighbors.
4. Sum up the returned values to get the total perimeter.
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
visit = set()
def dfs(i, j):
if i < 0 or j < 0 or i >= rows or j >= cols or grid[i][j] == 0:
return 1
if (i, j) in visit:
return 0
visit.add((i, j))
perim = dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i - 1, j)
return perim
for i in range(rows):
for j in range(cols):
if grid[i][j]:
return dfs(i, j)
return 0
Time & Space Complexity
- Time complexity: O(m∗n)
- Space complexity: O(m∗n)