Walls and Gates

Given a room grid where -1 is a wall, 0 is a gate, and INF represents an empty room, fill each empty room with the distance to its nearest gate. Pattern focus: Grid Graph Traversal. Run multi-source BFS from every gate simultaneously.

Input Format

rooms = 2D integer matrix

Output Format

matrix of minimum distances to nearest gate

Constraints

  • 1 <= rows * cols <= 10^5
  • rooms contains -1, 0, or INF.

Examples

Example 1:

Input:

rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]

Output:

[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

Explanation:

Distances are filled from the nearest gate.

Example 2:

Input:

rooms = [[0]]

Output:

[[0]]

Explanation:

A gate remains zero.

Example 3:

Input:

rooms = [[-1]]

Output:

[[-1]]

Explanation:

A wall stays unchanged.

Loading...
Walls and Gates - Graph Traversal DSA Problem