01 Matrix

Pattern: Grid graphs

medium

Find each cell's distance to the nearest 0 with one multi-source BFS: start with every 0 in the queue at distance 0. The first time BFS reaches a cell is its shortest distance.

The problem

Given a grid of 0s and 1s (with at least one 0), return a grid where each cell holds its distance to the nearest 0, moving up, down, left or right.

Think first

  • Why not BFS from every 1?
  • What if BFS starts from all 0s together?
  • Why is the first visit the shortest?

Hints

    Brute force, and why it fails

    BFS from every 1 to find its nearest 0: O((R × C)²).

    The key insight

    Reversing the question, from every 0 outwards at once, answers all cells in a single BFS.

    Dry run

    [[0, 0, 0], [0, 1, 0], [1, 1, 1]]. All six 0s start in the queue.

    Step 1 of 3

    The plan

    dist = 0 for 0s, -1 for others; queue = all 0s
    BFS: an unvisited neighbour gets dist + 1
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    Each cell is queued once.

    Edge cases

    • All zeros.
    • A single 0 in a corner.
    • One row.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[][] updateMatrix(int[][] mat) {
            int R = mat.length, C = mat[0].length;
            int[][] dist = new int[R][C];
            Queue<int[]> q = new ArrayDeque<>();
            for (int r = 0; r < R; r++)
                for (int c = 0; c < C; c++) {
                    if (mat[r][c] == 0) q.add(new int[]{r, c});   // every 0 is a source at distance 0
                    else dist[r][c] = -1;           // not reached yet
                }
            int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            while (!q.isEmpty()) {
                int[] cur = q.poll();
                for (int[] d : dirs) {
                    int r = cur[0] + d[0], c = cur[1] + d[1];
                    if (r >= 0 && c >= 0 && r < R && c < C && dist[r][c] == -1) {
                        dist[r][c] = dist[cur[0]][cur[1]] + 1;   // the first time BFS reaches it is the nearest 0
                        q.add(new int[]{r, c});
                    }
                }
            }
            return dist;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
            int R = static_cast<int>(mat.size()), C = static_cast<int>(mat[0].size());
            vector<vector<int>> dist(R, vector<int>(C, -1));   // -1: not reached yet
            queue<pair<int, int>> q;
            for (int r = 0; r < R; r++)
                for (int c = 0; c < C; c++)
                    if (mat[r][c] == 0) { dist[r][c] = 0; q.push(make_pair(r, c)); }   // every 0 is a source
            int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
            while (!q.empty()) {
                pair<int, int> cur = q.front();
                q.pop();
                for (int k = 0; k < 4; k++) {
                    int r = cur.first + dr[k], c = cur.second + dc[k];
                    if (r >= 0 && c >= 0 && r < R && c < C && dist[r][c] == -1) {
                        dist[r][c] = dist[cur.first][cur.second] + 1;   // the first time BFS reaches it is the nearest 0
                        q.push(make_pair(r, c));
                    }
                }
            }
            return dist;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:
            R, C = len(mat), len(mat[0])
            dist = [[0 if v == 0 else -1 for v in row] for row in mat]   # every 0 is a source; -1: not reached
            q = deque((r, c) for r in range(R) for c in range(C) if mat[r][c] == 0)
            while q:
                r, c = q.popleft()
                for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= x < R and 0 <= y < C and dist[x][y] == -1:
                        dist[x][y] = dist[r][c] + 1     # the first time BFS reaches it is the nearest 0
                        q.append((x, y))
            return dist

    Common mistakes

    • Starting from a single 0.
    • Not marking cells when they are queued.

    Similar problems