Problem Description
Given an m x n binary matrix mat, the goal is to return a matrix where each cell contains the distance from that cell to its nearest 0. The distance is measured in steps, moving only up, down, left, or right.
Key Insights
- Treat all 0s as starting points for a multi-source BFS.
- Update each neighboring cell's distance if a shorter distance is found.
- Utilize a queue to process cells in order of increasing distance.
- Ensure that each cell is processed only once by marking visited cells.
Space and Time Complexity
Time Complexity: O(mn) since each cell is processed once. Space Complexity: O(mn) for the queue and the answer matrix.
Solution
We use a multi-source Breadth-First Search (BFS) where every 0 in the matrix is initially added to the BFS queue. Each neighboring cell that is a 1 will have its distance updated to be one plus the distance of the current cell if it hasn’t been visited yet (or if a smaller distance is found). This ensures that the first time a 1 is reached, it is reached by the shortest path. Data structures used include a queue (or deque) for BFS and the matrix itself for storing distances.