#463
Island Perimeter
EasyArrayDepth-First SearchBreadth-First SearchMatrixDepth-First SearchBreadth-First SearchMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that each land cell contributes a fixed amount to the perimeter. By counting the number of land cells and their exposed edges directly, we can compute the perimeter more efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a perimeter counter to 0.
- 2Step 2: Iterate through each cell in the grid.
- 3Step 3: For each land cell (grid[i][j] == 1), check its four neighbors (up, down, left, right).
- 4Step 4: For each neighbor that is either water (0) or out of bounds, increment the perimeter counter.
- 5Step 5: Return the total perimeter counter.
solution.py18 lines
1# Full working Python code
2
3def islandPerimeter(grid):
4 perimeter = 0
5 rows, cols = len(grid), len(grid[0])
6 for i in range(rows):
7 for j in range(cols):
8 if grid[i][j] == 1:
9 # Check all four directions
10 if i == 0 or grid[i-1][j] == 0:
11 perimeter += 1 # Up
12 if i == rows - 1 or grid[i+1][j] == 0:
13 perimeter += 1 # Down
14 if j == 0 or grid[i][j-1] == 0:
15 perimeter += 1 # Left
16 if j == cols - 1 or grid[i][j+1] == 0:
17 perimeter += 1 # Right
18 return perimeterℹ
Complexity note: The time complexity is O(n) because we only iterate through each cell once. The space complexity is O(1) since we only use a constant amount of space for the perimeter counter.
- 1Each land cell contributes to the perimeter based on its neighboring cells.
- 2The grid is guaranteed to have only one island, simplifying the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.