01 Matrix

Given a binary matrix, return a matrix where each cell contains the distance to the nearest 0. Distances are measured using four-directional movement. Pattern focus: BFS. Perform a multi-source BFS from every zero cell and expand outward by layers.

Input Format

mat = 2D binary matrix

Output Format

matrix of distances to nearest zero

Constraints

  • 1 <= rows * cols <= 10^5
  • Each cell is 0 or 1.

Examples

Example 1:

Input:

mat = [[0,0,0],[0,1,0],[1,1,1]]

Output:

[[0,0,0],[0,1,0],[1,2,1]]

Explanation:

Each 1 is replaced by the distance to the nearest 0.

Example 2:

Input:

mat = [[1,1],[1,0]]

Output:

[[2,1],[1,0]]

Explanation:

Distances are measured to the closest zero.

Example 3:

Input:

mat = [[0]]

Output:

[[0]]

Explanation:

A single zero stays zero.

Loading...
01 Matrix - Graph Traversal DSA Problem