Map of Highest Peak — LeetCode 1765 Python Solution

MediumBreadth-First SearchArrayMatrix
Problem
#1765
Reading time
3 min

The problem

You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell.

Example

Input
isWater = [[0,1],[0,0]]
Output
[[1,0],[2,1]]
Explanation
The image shows the assigned heights of each cell.

Python solution

Python
class Solution:
    def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:
        m, n = len(isWater), len(isWater[0])
        ans = [[-1] * n for _ in range(m)]
        q = deque()
        for i, row in enumerate(isWater):
            for j, v in enumerate(row):
                if v:
                    q.append((i, j))
                    ans[i][j] = 0
        while q:
            i, j = q.popleft()
            for a, b in pairwise((-1, 0, 1, 0, -1)):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and ans[x][y] == -1:
                    ans[x][y] = ans[i][j] + 1
                    q.append((x, y))
        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 1765. Map of Highest Peak 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 1765. Map of Highest Peak?
LeetCode 1765. Map of Highest Peak is rated Medium on LeetCode.
What is the time complexity of LeetCode 1765. Map of Highest Peak?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1765. Map of Highest Peak?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1765. Map of Highest Peak cover?
LeetCode 1765. Map of Highest Peak is tagged 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