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
Visualization
Time & Space Complexity
Each cell is visited exactly once during BFS traversal
Queue can contain up to all cells in worst case, plus result matrix
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