01 Matrix

Medium · Graphs · Explanation and code example

Multi-Source Breadth-First Search

How it works

Start BFS from every zero simultaneously. Every step from this frontier adds one to the nearest-zero distance, so the first visit to a cell gives its minimum distance. Store distances in the matrix while a separate seen grid prevents repeat visits.

Steps

  1. Enqueue all zeros and mark them seen.
  2. Visit unvisited orthogonal neighbors at parent distance + 1.
  3. Mark when enqueueing and return the updated matrix.

Complexity

  • Time: O(rows × columns).
  • Space: O(rows × columns).

Things to watch for

  • Start from all zeros, rather than one zero.
  • Only orthogonal moves count.
  • This implementation overwrites the input matrix with distances.

Python code example

import collections

class Solution:
  def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:
    DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
    m = len(mat)
    n = len(mat[0])
    q = collections.deque()
    seen = [[False] * n for _ in range(m)]

    for i in range(m):
      for j in range(n):
        if mat[i][j] == 0:
          q.append((i, j))
          seen[i][j] = True

    while q:
      i, j = q.popleft()
      for dx, dy in DIRS:
        x = i + dx
        y = j + dy
        if x < 0 or x == m or y < 0 or y == n:
          continue
        if seen[x][y]:
          continue
        mat[x][y] = mat[i][j] + 1
        q.append((x, y))
        seen[x][y] = True

    return mat

C++ code example

class Solution {
 public:
  vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = mat.size();
    const int n = mat[0].size();
    queue<pair<int, int>> q;
    vector<vector<bool>> seen(m, vector<bool>(n));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (mat[i][j] == 0) {
          q.emplace(i, j);
          seen[i][j] = true;
        }

    while (!q.empty()) {
      const auto [i, j] = q.front();
      q.pop();
      for (const auto& [dx, dy] : kDirs) {
        const int x = i + dx;
        const int y = j + dy;
        if (x < 0 || x == m || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        mat[x][y] = mat[i][j] + 1;
        q.emplace(x, y);
        seen[x][y] = true;
      }
    }

    return mat;
  }
};
Source and license

Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations