Problem 1765

Abstract / Summary

Given a matrix of heights, create a new matrix where each cell shows how far it is from the nearest highest peak.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1765.py

class Solution:
    def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:
        width  = len(isWater[0])
        height = len(isWater)

        # identify all water cells
        # convert water from +1 to 0 and land from 0 to -1
        unknown = -1
        todo = set()
        for y in range(height):
            for x in range(width):
                if isWater[y][x] == 1:
                    todo.add((x, y))
                    isWater[y][x] = 0
                else:
                    isWater[y][x] = unknown

        seen  = set()
        level = 0 # water
        while todo:
            next = set()

            for x, y in todo:
                if (x, y) in seen:
                    continue
                seen.add((x, y))
                isWater[y][x] = level

                if x > 0 and isWater[y][x - 1] == unknown:
                    next.add((x - 1, y))
                if y > 0 and isWater[y - 1][x] == unknown:
                    next.add((x, y - 1))
                if x < width - 1  and isWater[y][x + 1] == unknown:
                    next.add((x + 1, y))
                if y < height - 1 and isWater[y + 1][x] == unknown:
                    next.add((x, y + 1))

            todo   = next
            level += 1
        return isWater
40 lines | 1327 bytes | submitted December 20, 2023 | GitHub   9% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the height map for a terrain where water cells are given as 1 and land cells as 0. It transforms the input matrix in-place, assigning a height of 0 to water and increasing integer heights to land cells based on their minimum Manhattan distance to any water cell. The algorithm proceeds level by level, expanding outward from all water cells simultaneously, which guarantees that each land cell receives the smallest possible height.

Key Steps

The first phase determines the dimensions of the grid and prepares the data structures used for the breadth-first expansion.

width  = len(isWater[0])
height = len(isWater)

During the initialization loop each cell is examined. Water cells are added to a frontier set called todo and are immediately set to height 0. All land cells are marked with a sentinel value -1 (named unknown) to indicate that their height has not yet been computed.

unknown = -1
todo = set()
for y in range(height):
    for x in range(width):
        if isWater[y][x] == 1:
            todo.add((x, y))
            isWater[y][x] = 0
        else:
            isWater[y][x] = unknown

The main loop performs a level-order traversal. A seen set prevents processing the same cell more than once, while level tracks the current height being assigned. For each cell in the current frontier, the algorithm writes the current level into the matrix and inspects its four orthogonal neighbours. Any neighbour still marked as unknown is added to a next set, which becomes the frontier for the following iteration.

seen  = set()
level = 0
while todo:
    next = set()
    for x, y in todo:
        if (x, y) in seen:
            continue
        seen.add((x, y))
        isWater[y][x] = level
        if x > 0 and isWater[y][x - 1] == unknown:
            next.add((x - 1, y))
        if y > 0 and isWater[y - 1][x] == unknown:
            next.add((x, y - 1))
        if x < width - 1  and isWater[y][x + 1] == unknown:
            next.add((x + 1, y))
        if y < height - 1 and isWater[y + 1][x] == unknown:
            next.add((x, y + 1))
    todo   = next
    level += 1

When the frontier becomes empty, every cell has been assigned a height, and the modified matrix is returned.

return isWater

Edge Cases Handled

The algorithm gracefully processes grids where all cells are water; the initial todo set contains every coordinate, the loop runs once, and the matrix remains filled with zeros. Conversely, when the grid contains no water, the initial todo set is empty, the while-loop is skipped, and the matrix stays filled with the sentinel -1. However, because the sentinel is replaced only when a neighbour becomes known, a completely land-only grid will end with all cells set to increasing heights starting from the outermost layer, effectively treating the nonexistent water as a virtual source at distance zero.

Single-row and single-column grids are supported because the neighbour checks respect boundary conditions (x > 0, x < width - 1, y > 0, y < height - 1). Rectangular shapes of any aspect ratio are processed without modification to the core logic.

Performance Optimizations

The implementation modifies the input matrix directly, eliminating the need for an auxiliary result array and reducing memory pressure. The use of a set for the frontier (todo) enables O(1) membership tests and prevents duplicate entries when multiple water cells share a neighbour. The seen set further guarantees that each cell is processed exactly once, avoiding redundant work in dense water configurations. By advancing the frontier level by level and incrementing a single level counter, the algorithm avoids recomputing distances for already visited cells, ensuring that each assignment reflects the minimal distance to water. This approach yields an efficient traversal that scales linearly with the number of cells in the grid.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big sheet of graph paper that represents a map. Some squares on this map are filled with water, and the rest are just empty land waiting to become tall mountains. The goal is to see how far each piece of land is from the nearest water.

First, the code looks at every square on the map one by one. If a square has water, it marks it with a zero because water is at the very bottom level. If a square is land, it marks it with a special minus one to show that it is still waiting for a height to be assigned.

After finding all the water, the code starts a little game of tag that grows outward. It looks at all the squares next to the water and says these are one step away, so they get a height of one. Then it looks at the squares next to those and says they are two steps away, so they get a height of two. It keeps going like this, pushing outward from the water in all directions, layer by layer.

As it moves, it makes sure not to visit the same spot twice so everything stays organized. By the time it finishes looking at every single square, the map is filled with numbers showing how high each mountain peak is compared to the water. It is almost like watching ripples in a pond grow wider and wider until they reach the very edge of the map.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.59 | σ = 1.31

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
withaarzoo C++
27 links | 15 authors | 9 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

20 solutions   December 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality