Imagine you're standing in a maze of 0s and 1s, and you need to find the shortest path from every cell to the nearest safe zone (0). This is exactly what the 01 Matrix problem asks you to solve!

Given an m × n binary matrix mat containing only 0s and 1s, your task is to calculate the minimum distance from each cell to the nearest 0. Two cells are considered adjacent if they share a common edge (up, down, left, right), and each step has a distance of 1.

Goal: Transform the matrix so that each cell contains the distance to the nearest 0.

Example: If you have a matrix like [[0,0,0],[0,1,0],[1,1,1]], the cell at position (1,1) has a distance of 1 to reach any 0, while the cell at (2,2) has a distance of 2.

Input & Output

example_1.py — Basic Matrix
$ Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
💡 Note: The center cell (1,1) is already surrounded by zeros at distance 1, so its value becomes 1. All other cells are already zeros.
example_2.py — Complex Matrix
$ Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
💡 Note: Bottom row: (2,0) and (2,2) are distance 1 from nearest zeros, while (2,1) is distance 2 from the nearest zeros.
example_3.py — Single Element
$ Input: mat = [[0]]
Output: [[0]]
💡 Note: Edge case with single zero element - distance to itself is 0.

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

Visualization

Tap to expand
01 Matrix - BFS Approach INPUT Binary Matrix (3x3) 0 0 0 0 1 0 0 0 0 = Safe zone (0) = Need distance (1) Input: [[0,0,0],[0,1,0],[0,0,0]] ALGORITHM STEPS 1 Initialize Queue Add all 0s to queue Set dist[0]=0, dist[1]=INF 2 Multi-source BFS Process cells level by level Expand from all 0s at once 3 Check 4 Neighbors Up, Down, Left, Right If unvisited: dist = prev + 1 4 Update Distance Store min distance found Add updated cell to queue BFS Queue: 0,0 0,1 ... 1,1 --> Process FINAL RESULT Distance Matrix 0 0 0 0 1 0 0 0 0 Cell (1,1) has distance 1 Nearest 0 is 1 step away OK - Complete! Output: [[0,0,0],[0,1,0],[0,0,0]] Key Insight: Multi-source BFS starts from ALL zeros simultaneously, propagating outward layer by layer. This guarantees each cell finds its nearest 0 in O(m*n) time - much faster than running BFS from each 1 separately. The first time we reach a cell, we have the minimum distance! TutorialsPoint - 01 Matrix | BFS Approach Time: O(m*n) | Space: O(m*n)
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.9K Views
High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen