148: Walls and Gates

Given a 2D matrix, the matrix contains following values:

  • -1 - a wall
  • 0 - a gate
  • R - an empty room. R equals 2147483647

fill each empty room with the distance to the nearest gate, if it's impossible to reach a gate, a value should be equal R

 

Example 1

Input:    0,  -1,  -1,   0,  0 
         -1,   R,  -1,   0,  0
          R,  -1,   0,  -1,  0
          0,   R,   R,  -1,  0

Output:   0,  -1,  -1,   0,  0
         -1,   R,  -1,   0,  0
          1,  -1,   0,  -1,  0
          0,   1,   1,  -1,  0 

Example 2

Input:    [[0, 0, -1, R, 0]]

Output:   [[0, 0, -1, 1, 0]]
Difficulty:Medium
Topic:Graph
Problem #:148