01 Matrix

Medium Graphs Multi source BFS Original on LeetCode

Reported atDoorDashOracle

01 Matrix is a medium graphs problem solved with the multi source bfs pattern. The best approach, optimal (multi-source bfs from all 0s), runs in O(m · n) time and O(m · n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from bfs from every 1 up.

Problem

Given a binary matrix, return a matrix of the same size where each cell holds the distance to the nearest 0 (moving up, down, left or right).

Examples

Example 1

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

Example 2

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

Constraints

  • 1 <= m · n <= 10^4; at least one 0.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
BFS from every 1O((m · n)²)O(m · n)
Optimal (multi-source BFS from all 0s)O(m · n)O(m · n)

1BFS from every 1

TimeO((m · n)²)
SpaceO(m · n)

For each cell with 1, BFS until you reach a 0.

  1. For each 1, BFS outward; record the level at which a 0 appears.
class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[][] out = new int[m][n];
        int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) continue;
                boolean[][] seen = new boolean[m][n];
                Queue<int[]> q = new ArrayDeque<>();
                q.add(new int[] { i, j, 0 });
                seen[i][j] = true;
                while (!q.isEmpty()) {
                    int[] c = q.poll();
                    if (mat[c[0]][c[1]] == 0) { out[i][j] = c[2]; break; }
                    for (int[] d : dirs) {
                        int r = c[0] + d[0], k = c[1] + d[1];
                        if (r >= 0 && k >= 0 && r < m && k < n && !seen[r][k]) {
                            seen[r][k] = true;
                            q.add(new int[] { r, k, c[2] + 1 });
                        }
                    }
                }
            }
        return out;
    }
}

2Optimal (multi-source BFS from all 0s)

TimeO(m · n)
SpaceO(m · n)

Put every 0 in the queue with distance 0 and mark every 1 as unknown (-1). BFS outward; the first time a cell is reached, its distance is final.

  1. dist = 0 for zeros (enqueued), -1 for ones.
  2. Poll; for each neighbour with dist -1, set dist = cur + 1 and enqueue.
class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        Queue<int[]> q = new ArrayDeque<>();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) q.add(new int[] { i, j });
                else mat[i][j] = -1;
            }
        int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
        while (!q.isEmpty()) {
            int[] c = q.poll();
            for (int[] d : dirs) {
                int r = c[0] + d[0], k = c[1] + d[1];
                if (r >= 0 && k >= 0 && r < m && k < n && mat[r][k] == -1) {
                    mat[r][k] = mat[c[0]][c[1]] + 1;
                    q.add(new int[] { r, k });
                }
            }
        }
        return mat;
    }
}

Edge cases to test

  • A single 0 far from most cells

Hints

Hint 1

Instead of a BFS from every 1, run one BFS starting from all 0s at the same time.

FAQ

What is the best time complexity for 01 Matrix?

Optimal (multi-source BFS from all 0s) runs in O(m · n) time and O(m · n) extra space.

Which pattern does 01 Matrix use?

It is a graphs problem that uses the multi source bfs pattern. Other problems with the same pattern: Rotting Oranges, Pacific Atlantic Water Flow, Escape the Spreading Fire.

Is there a brute force solution for 01 Matrix?

Yes. BFS from every 1 takes O((m · n)²) time and O(m · n) space. For each cell with 1, BFS until you reach a 0.

Which edge cases should I test for 01 Matrix?

A single 0 far from most cells.