Skip to main content

01 Matrix - Solution & Explanation

MediumArrayDynamic ProgrammingBreadth-First SearchMatrix20 min readAsked at: Amazon, Microsoft, Apple +11
Practice this problem

Problem Statement

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two cells sharing a common edge is 1.

 

Example 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • There is at least one 0 in mat.

 

Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/

Approach Overview

Problem Overview: You get an m x n binary matrix containing only 0 and 1. For every cell containing 1, compute the distance to the nearest 0. Distance is measured using 4-directional moves (up, down, left, right). The result is another matrix where each cell stores the shortest distance to a zero.

Approach 1: Breadth-First Search (Multi-Source BFS) (Time: O(m*n), Space: O(m*n))

This problem becomes straightforward once you flip the perspective. Instead of starting BFS from every 1, start from every 0 simultaneously. Push all zero cells into a queue and run a multi-source Breadth-First Search. Each expansion updates neighboring cells with distance current + 1. Because BFS explores level by level, the first time a cell is reached guarantees the shortest path to a zero. Use a queue and iterate through the grid once to initialize it. Then repeatedly pop cells, check their four neighbors, and update distances if they haven't been assigned yet. Each cell enters the queue at most once, giving linear time complexity.

This approach works well because BFS naturally computes shortest paths in an unweighted grid. Since all edges have equal cost (1 step), BFS guarantees minimal distance without extra bookkeeping. For grid shortest-path problems involving nearest targets, multi-source BFS is often the cleanest and most interview-friendly pattern. The grid itself can store distances, so only a queue is required for traversal.

Approach 2: Dynamic Programming Two-Pass Scan (Time: O(m*n), Space: O(1) extra)

The same result can be computed using Dynamic Programming with two directional passes. Initialize a distance matrix with a large value for cells containing 1 and 0 for zero cells. First pass: iterate top-left to bottom-right. For each cell, check top and left neighbors and update the distance using min(current, neighbor + 1). Second pass: iterate bottom-right to top-left and check bottom and right neighbors. These two passes propagate the shortest distance information across the grid.

The key insight is that the shortest path to a zero must come from one of the four directions. Splitting the updates into two directional sweeps ensures all possibilities are covered. This method avoids a queue and works purely with iterative updates over the matrix. Time complexity remains linear because each cell is processed a constant number of times.

Recommended for interviews: Multi-source BFS is the approach most interviewers expect. It demonstrates understanding of grid traversal and shortest-path patterns using BFS. The dynamic programming solution is equally optimal but slightly less intuitive unless you already recognize the two-pass DP pattern used in grid distance problems.

Approach 1: Breadth-First Search (BFS) Approach

The BFS approach involves initializing a queue with all positions of zeros in the matrix, since the distance from any zero to itself is zero. From there, perform a level-order traversal (BFS) to update the distances of the cells that are accessible from these initial zero cells. This approach guarantees that each cell is reached by the shortest path.

In the C implementation, we use a queue to perform a BFS starting from all cells with 0. We then update neighboring cells with the smallest distance possible, propagating the minimum distances to eventually fill out the entire matrix with correct values.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m * n), as each cell is processed at most once.
Space Complexity: O(m * n), for storing the resulting distance matrix and the BFS queue.

Try this approach in the editor →

Approach 2: Dynamic Programming Approach

The dynamic programming (DP) approach updates the matrix by considering each cell from four possible directions, iterating twice over the matrix to propagate the minimum distances. First, traverse from top-left to bottom-right, and then from bottom-right to top-left, ensuring a comprehensive minimum distance calculation.

In this C code, distance calculation progresses first from the top-left to bottom-right. We then perform a second pass from bottom-right to top-left to integrate the shortest distances possible from alternate directions. The use of INT_MAX - 1 is a sufficient surrogate for infinity.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m * n)
Space Complexity: O(m * n)

Try this approach in the editor →

Approach 3: BFS

We create a matrix ans of the same size as mat and initialize all elements to -1.

Then, we traverse mat, adding the coordinates (i, j) of all 0 elements to the queue q, and setting ans[i][j] to 0.

Next, we use Breadth-First Search (BFS), removing an element (i, j) from the queue and traversing its four directions. If the element in that direction (x, y) satisfies 0 leq x < m, 0 leq y < n and ans[x][y] = -1, then we set ans[x][y] to ans[i][j] + 1 and add (x, y) to the queue q.

Finally, we return ans.

The time complexity is O(m times n), and the space complexity is O(m times n). Here, m and n are the number of rows and columns in the matrix mat, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Breadth-First Search (BFS) Approach

Time Complexity: O(m * n), as each cell is processed at most once.
Space Complexity: O(m * n), for storing the resulting distance matrix and the BFS queue.

Dynamic Programming Approach

Time Complexity: O(m * n)
Space Complexity: O(m * n)

BFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Multi-Source BFSO(m*n)O(m*n)Best general solution for shortest distance in grids; very intuitive in interviews
Dynamic Programming Two-PassO(m*n)O(1) extraWhen avoiding queue-based traversal or optimizing memory usage

Video Solution

Leetcode 542. 01 Matrix - Python • HelmyCodeCamp • 26,344 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is 01 Matrix easy or hard?
01 Matrix is categorized as a medium problem. The challenge lies in recognizing that BFS should start from all zero cells simultaneously instead of running a search from each one cell. Once that insight is clear, the implementation becomes straightforward.
01 Matrix Python/Java solution
Python and Java solutions typically implement multi-source BFS using a queue. Initialize the queue with all zero cells, then expand in four directions while updating distances. The same logic works across C++, JavaScript, and other languages because it relies on standard queue-based BFS traversal.
How to solve 01 Matrix in O(n)?
Treat the grid as an unweighted graph and run multi-source BFS starting from all zero cells. Each step updates neighbors with distance +1 and pushes them into the queue. Since every cell is visited at most once, the algorithm runs in O(m*n) time, which is linear in the number of cells.
What is the best approach for 01 Matrix?
The most common solution uses multi-source Breadth-First Search. All cells containing 0 are pushed into a queue first, then BFS expands outward to update distances for nearby cells. Because BFS processes nodes level by level, the first distance assigned to each cell is guaranteed to be the shortest. This approach runs in O(m*n) time.
Is 01 Matrix asked at Google/Amazon/Meta?
01 Matrix is a common grid shortest-path problem used by companies such as Amazon, Google, and Meta during coding interviews. It tests BFS fundamentals, matrix traversal, and the ability to recognize multi-source shortest-path patterns.
What data structure is used in 01 Matrix?
The BFS solution uses a queue to process cells in layers while computing shortest distances. The grid or a separate distance matrix stores computed values. The dynamic programming approach instead relies on iterative updates in the matrix without using additional data structures.
What is the time complexity of 01 Matrix?
Both optimal solutions run in O(m*n) time where m and n are the matrix dimensions. Each cell is processed a constant number of times either through BFS traversal or DP updates. Space complexity is O(m*n) for the BFS queue and distance storage, while the DP approach can reduce extra space to O(1).

Ready to solve this problem?

Practice 01 Matrix with our built-in code editor and test cases.

Practice on FleetCode