#C11894. Walls and Gates
Walls and Gates
Walls and Gates
You are given a 2D grid that represents a map of rooms, walls, and gates. Each cell in the grid can be:
-1
representing a wall which you cannot pass through.0
representing a gate.2147483647
(representing infinity) representing an empty room. You can assume that2147483647
is used for empty rooms.
Your task is to fill each empty room with the number of steps to reach its nearest gate. If it is impossible for an empty room to reach any gate, leave it as 2147483647
.
You are required to use an efficient algorithm (e.g., Breadth-First Search) to solve the problem.
inputFormat
The input is read from standard input (stdin
) and has the following format:
- The first line contains a single integer
T
representing the number of test cases. - For each test case, the first line contains two space-separated integers
m
andn
which denote the number of rows and columns of the grid respectively. - This is followed by
m
lines, each containingn
space-separated integers. Each integer will be either-1
,0
, or2147483647
.
outputFormat
For each test case, output the modified grid to standard output (stdout
) in the following format:
- Output
m
lines where each line containsn
space-separated integers representing the final state of the grid after filling the empty rooms with the distance to the nearest gate. - The order of the test cases in the output should be the same as in the input.
4
4 4
2147483647 -1 0 2147483647
2147483647 2147483647 2147483647 -1
2147483647 -1 2147483647 -1
0 -1 2147483647 2147483647
2 2
0 -1
-1 0
2 2
-1 -1
-1 -1
2 2
2147483647 0
2147483647 0
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
0 -1
-1 0
-1 -1
-1 -1
1 0
1 0
</p>