 All Problems
Walls and Gates
medium
graph
breadth-first search
matrix
facebook
google
amazon

You are given an m × n grid rooms initialized with the following values:

  • -1 — a Wall or an obstacle.
  • 0 — a Gate.
  • INF (2147483647) — an empty room.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, leave it as INF.

Example:

Input:
4 4
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF

Output:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4

Constraints:

  • 1 ≤ m, n ≤ 250
  • rooms[i][j] is -1, 0, or 2147483647

Input format: First line: m n. Then m lines with n values ("INF" or integer).

Output format: Modified grid — same format.

Run to check your code against the sample cases, or submit to run every case