01 Matrix
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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| BFS from every 1 | O((m · n)²) | O(m · n) |
| Optimal (multi-source BFS from all 0s) | O(m · n) | O(m · n) |
1BFS from every 1
O((m · n)²)O(m · n)For each cell with 1, BFS until you reach a 0.
- 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;
}
}class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
out = [[0] * n for _ in range(m)]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
continue
seen = [[False] * n for _ in range(m)]
q = deque([(i, j, 0)])
seen[i][j] = True
while q:
c = q.popleft()
if mat[c[0]][c[1]] == 0:
out[i][j] = c[2]
break
for d in dirs:
r, k = c[0] + d[0], c[1] + d[1]
if r >= 0 and k >= 0 and r < m and k < n and not seen[r][k]:
seen[r][k] = True
q.append((r, k, c[2] + 1))
return outclass Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> out(m, vector<int>(n, 0));
int dirs[4][2] = { { 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;
vector<vector<bool>> seen(m, vector<bool>(n, false));
queue<array<int, 3>> q;
q.push({i, j, 0});
seen[i][j] = true;
while (!q.empty()) {
array<int, 3> c = q.front();
q.pop();
if (mat[c[0]][c[1]] == 0) { out[i][j] = c[2]; break; }
for (auto& 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.push({r, k, c[2] + 1});
}
}
}
}
return out;
}
};function updateMatrix(mat) {
const m = mat.length, n = mat[0].length;
const out = Array.from({ length: m }, () => new Array(n).fill(0));
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (mat[i][j] === 0) continue;
const seen = Array.from({ length: m }, () => new Array(n).fill(false));
const q = [[i, j, 0]];
let head = 0;
seen[i][j] = true;
while (head < q.length) {
const c = q[head++];
if (mat[c[0]][c[1]] === 0) { out[i][j] = c[2]; break; }
for (const d of dirs) {
const 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.push([r, k, c[2] + 1]);
}
}
}
}
return out;
}2Optimal (multi-source BFS from all 0s)
O(m · n)O(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.
- dist = 0 for zeros (enqueued), -1 for ones.
- 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;
}
}class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
q = deque()
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
q.append((i, j))
else:
mat[i][j] = -1
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while q:
c = q.popleft()
for d in dirs:
r, k = c[0] + d[0], c[1] + d[1]
if r >= 0 and k >= 0 and r < m and k < n and mat[r][k] == -1:
mat[r][k] = mat[c[0]][c[1]] + 1
q.append((r, k))
return matclass Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
queue<pair<int, int>> q;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0) q.push({i, j});
else mat[i][j] = -1;
}
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (!q.empty()) {
auto c = q.front();
q.pop();
for (auto& d : dirs) {
int r = c.first + d[0], k = c.second + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && mat[r][k] == -1) {
mat[r][k] = mat[c.first][c.second] + 1;
q.push({r, k});
}
}
}
return mat;
}
};function updateMatrix(mat) {
const m = mat.length, n = mat[0].length;
const q = [];
let head = 0;
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (mat[i][j] === 0) q.push([i, j]);
else mat[i][j] = -1;
}
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (head < q.length) {
const c = q[head++];
for (const d of dirs) {
const 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.push([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.