Island Perimeter — LeetCode 463 Python Solution
EasyDepth-First SearchBreadth-First SearchArrayMatrix
- Problem
- #463
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given 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).
Example
- 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.
Python solution
Python
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
ans += 4
if i < m - 1 and grid[i + 1][j] == 1:
ans -= 2
if j < n - 1 and grid[i][j + 1] == 1:
ans -= 2
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 463. Island Perimeter is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 463. Island Perimeter?
- LeetCode 463. Island Perimeter is rated Easy on LeetCode.
- What is the time complexity of LeetCode 463. Island Perimeter?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 463. Island Perimeter?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 463. Island Perimeter cover?
- LeetCode 463. Island Perimeter is tagged Depth-First Search, Breadth-First Search, Array and Matrix on LeetCode.