AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

01 Matrix

The key idea

Run one breadth-first search from ALL the 0 cells at once. Seed the queue with every 0 (distance 0), then expand outward. Because every source starts at the same level, the first time BFS reaches a 1 cell it does so along the shortest path, so that cell's distance is final the moment it is dequeued's neighbor.

Problem

Given an m x n binary matrix mat, return a matrix of the same size where each entry is the distance from that cell to the nearest cell containing 0. The distance between two cells that share a side is 1. Every 0 cell has distance 0, and you may assume the matrix contains at least one 0.

Constraints

Examples

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

Complexity

Time: O(m * n) Space: O(m * n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems