Island Perimeter — LeetCode 463 Python Solution

EasyDepth-First SearchBreadth-First SearchArrayMatrix
Problem
#463
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview