Problem 542

Abstract / Summary

Given a matrix of 0s and 1s, create a new matrix showing the distance to the nearest 0 for each cell

Note

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

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
32 lines | 1194 bytes | submitted August 17, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Dynamic Programming
  • 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.08 | σ = 1.47

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
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++
34 links | 19 authors | 9 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 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