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
Difficulty
and has an acceptance rate of about 76% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 542: 01 Matrix
Solved On The Same Day
- problem 1752: Check if Array Is Sorted and Rotated
- problem 1791: Find Center of Star Graph
- problem 1971: Find if Path Exists in Graph
- problem 1984: Minimum Difference Between Highest and Lowest of K Scores
- problem 2446: Determine if Two Events Have Conflict
- problem 2706: Buy Two Chocolates
- problem 2839: Check if Strings Can be Made Equal With Operations I
- problem 684: Redundant Connection
- problem 1008: Construct Binary Search Tree from Preorder Traversal
- problem 1026: Maximum Difference Between Node and Ancestor
- problem 1034: Coloring A Border
- problem 1625: Lexicographically Smallest String After Applying Operations
- problem 2192: All Ancestors of a Node in a Directed Acyclic Graph
- problem 2477: Minimum Fuel Cost to Report to the Capital
- problem 2492: Minimum Score of a Path Between Two Cities
- problem 2596: Check Knight Tour Configuration
- problem 2658: Maximum Number of Fish in a Grid
- problem 827: Making A Large Island
- problem 1036: Escape a Large Maze
Extra
- 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