Algo-Sim › Grid Graphs

01 Matrix

Medium · Grid Graphs · step through it in Java, Python and C++ on your own input

Distance from every cell to its nearest 0: one multi-source BFS that starts from all the 0s together.

Problem

Given a grid of 0s and 1s, return a grid of the same size where each cell holds the number of steps (up, down, left or right) to the nearest 0. The grid contains at least one 0.

Constraints

Edge cases to test

Follow-up questions

Is there a non-BFS method?
Two DP passes: top-left to bottom-right, then the reverse, each taking 1 + the best neighbour seen: O(mn), O(1) extra.
Why not BFS from every 1?
That repeats work: O((mn)²). Multi-source BFS from the 0s is O(mn).

Solution

Java

public int[][] updateMatrix(int[][] mat) {
    int rows = mat.length, cols = mat[0].length;
    int[][] dist = new int[rows][cols];
    int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
    Queue<int[]> queue = new ArrayDeque<>();
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (mat[r][c] == 0) queue.offer(new int[] { r, c });
            else dist[r][c] = -1;  // not reached yet
        }
    }
    while (!queue.isEmpty()) {
        int[] cell = queue.poll();
        for (int[] d : dirs) {
            int nr = cell[0] + d[0], nc = cell[1] + d[1];
            if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || dist[nr][nc] != -1) continue;
            dist[nr][nc] = dist[cell[0]][cell[1]] + 1;
            queue.offer(new int[] { nr, nc });
        }
    }
    return dist;
}

Python

from collections import deque

def update_matrix(mat):
    rows, cols = len(mat), len(mat[0])
    dist = [[0] * cols for _ in range(rows)]
    dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    queue = deque()
    for r in range(rows):
        for c in range(cols):
            if mat[r][c] == 0:
                queue.append((r, c))
            else:
                dist[r][c] = -1  # not reached yet
    while queue:
        cr, cc = queue.popleft()
        for dr, dc in dirs:
            nr, nc = cr + dr, cc + dc
            if not (0 <= nr < rows and 0 <= nc < cols) or dist[nr][nc] != -1:
                continue
            dist[nr][nc] = dist[cr][cc] + 1
            queue.append((nr, nc))
    return dist

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
        int rows = int(mat.size()), cols = int(mat[0].size());
        vector<vector<int>> dist(rows, vector<int>(cols));
        vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        deque<pair<int, int>> queue;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (mat[r][c] == 0)
                    queue.push_back({r, c});
                else
                    dist[r][c] = -1;
            }
        }
        while (!queue.empty()) {
            auto [r, c] = queue.front();
            queue.pop_front();
            for (vector<int> &d : dirs) {
                int nr = r + d[0], nc = c + d[1];
                if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || dist[nr][nc] != -1)
                    continue;
                dist[nr][nc] = dist[r][c] + 1;
                queue.push_back({nr, nc});
            }
        }
        return dist;
    }
};

More Grid Graphs problems