C++ 0542.cpp
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
width = len(mat[0])
height = len(mat)
dist = [[99999 for i in range(width)] for j in range(height)]
todo = []
for y in range(height):
for x in range(width):
if mat[y][x] == 0:
dist[y][x] = 0
todo.append([y, x])
iteration = 0
while todo:
iteration += 1
process = todo
todo = []
for (y, x) in process:
if x > 0 and dist[y][x-1] > iteration:
dist[y][x-1] = iteration
todo.append([y, x-1])
if y > 0 and dist[y-1][x] > iteration:
dist[y-1][x] = iteration
todo.append([y-1, x])
if x < width-1 and dist[y][x+1] > iteration:
dist[y][x+1] = iteration
todo.append([y, x+1])
if y < height-1 and dist[y+1][x] > iteration:
dist[y+1][x] = iteration
todo.append([y+1, x])
return dist
Difficulty
and has an acceptance rate of about 54% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Dynamic Programming
- 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 minimum distance from each cell containing a 1 to the nearest cell containing a 0 in a binary matrix. It follows a breadth-first expansion from all zero cells simultaneously, updating a distance matrix until every reachable cell has been assigned its shortest distance. The algorithm terminates when no further updates are possible.
Initialization
The dimensions of the input matrix are captured first:
width = len(mat[0])
height = len(mat)
A distance matrix dist is created with a large sentinel value (99999) to represent “unvisited” cells:
dist = [[99999 for i in range(width)] for j in range(height)]
A list todo is prepared to hold the frontier of cells that will be processed in the first iteration. The code scans the entire matrix; whenever a zero is encountered, the corresponding entry in dist is set to 0 and the cell coordinates are added to todo:
for y in range(height):
for x in range(width):
if mat[y][x] == 0:
dist[y][x] = 0
todo.append([y, x])
At this point the algorithm has identified all sources for the breadth-first search.
Iterative Expansion
An iteration counter iteration is introduced to represent the current distance being propagated outward from the zero cells:
iteration = 0
while todo:
iteration += 1
process = todo
todo = []
for (y, x) in process:
# neighbor checks follow
During each loop, process holds the cells that were discovered in the previous step, and todo will collect the cells that become reachable at the new distance iteration.
Neighbor Exploration
For each cell (y, x) in process, the four orthogonal neighbors are examined. The code checks bounds and whether the neighbor’s current distance exceeds the new candidate distance (iteration). If so, the neighbor’s distance is updated and the neighbor is queued for the next round:
if x > 0 and dist[y][x-1] > iteration:
dist[y][x-1] = iteration
todo.append([y, x-1])
if y > 0 and dist[y-1][x] > iteration:
dist[y-1][x] = iteration
todo.append([y-1, x])
if x < width-1 and dist[y][x+1] > iteration:
dist[y][x+1] = iteration
todo.append([y, x+1])
if y < height-1 and dist[y+1][x] > iteration:
dist[y+1][x] = iteration
todo.append([y+1, x])
These conditional updates guarantee that each cell’s distance is set exactly once-the first time it is reached, which corresponds to the shortest possible distance because the expansion proceeds level by level.
Completion
When todo becomes empty, no further cells can be improved, and the fully populated distance matrix is returned:
return dist
Edge Cases Handled
The algorithm gracefully handles matrices that consist entirely of zeros. In that scenario the initial scan populates todo with every cell, each distance is set to 0, and the while-loop terminates immediately because no neighbor will have a larger distance than the current iteration.
If the matrix contains only ones, the initial todo list remains empty, the while-loop never executes, and the distance matrix retains the sentinel value for every cell. This reflects the fact that no zero is reachable, and the sentinel serves as a clear indicator of “infinite” distance.
Boundary cells are protected by explicit index checks (x > 0, y > 0, x < width-1, y < height-1). These conditions prevent out-of-range accesses when exploring neighbors at the edges of the matrix.
Performance Optimizations
The code avoids revisiting cells whose distance has already been established. By comparing the neighbor’s current distance against the current iteration count, it ensures that each cell is enqueued at most once. This eliminates redundant work and keeps the number of processed entries proportional to the number of cells in the matrix.
Using a single list todo that is swapped each iteration (process = todo; todo = []) reduces the overhead of creating new containers for each level of expansion. The algorithm reuses the same list objects, which helps with memory allocation patterns and improves cache locality.
The sentinel value 99999 is chosen to be larger than any possible distance in a reasonably sized matrix, allowing the simple > comparison to serve both as a “unvisited” flag and as a guard against unnecessary updates. This eliminates the need for a separate boolean visited matrix, thereby saving memory.
The breadth-first nature of the expansion guarantees that the first time a cell is reached, the distance assigned is minimal. Consequently, the algorithm does not need to perform any backtracking or additional passes, which contributes to its overall efficiency.
ELI5 - Simplified Explanation
Imagine you have a big grid of squares on the floor. Some squares have a zero painted on them, and the other squares are empty. You want to figure out how many steps it takes to travel from any empty square to the nearest square with a zero.
First, you look at every square in the grid. If you find a zero, you stand on it and put a zero in a notebook to remember that you are already home. You also add that spot to a list of places to visit.
Next, you start a game of tag. You look at all the squares you just visited and check their neighbors. If a neighbor is empty and does not have a number in the notebook yet, you run to that neighbor, mark down that it took one step to get there, and add that neighbor to the list for the next round.
You continue this by looking at all the neighbors of your new spots. For every empty space you find, you write down how many steps it took to reach it. Because you always look at neighbors further away after finishing the close ones, you are guaranteed to find the shortest path. You keep playing this game until every single square on the grid has a number written down that shows how far away the closest zero is.
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 | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | everthis | JS | ||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| vthwang | Java | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| vthwang | Java | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1730: Shortest Path to Get Food
- problem 1765: Map of Highest Peak
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
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