You are given a room as a grid of 1βs and 0βs. 1 indicating blocked cell and 0 indicating a free cell. There is a bomb in the X'th row from the top and Yβth column from the left. The bomb went off and smoke was starting to spread. In one sec smoke can spread to an adjacent cell if the adjacent cell has 0 in it. The bomb is always at the free cell.
Find the minimum time for the smoke to spread across all the reachable cells. A cell is reachable from another cell if you can travel from one cell to another via cells containing 0βs.
For example:
GRID=[[1,1,0,1],
[1,0,0,0],
[1,1,0,1]]
X,Y= (2, 3)
ANS = 2
In 1βst sec smoke will spread to (1, 3), (3, 3), (2, 2), (2, 4)
In 2βnd sec smoke will spread to (2, 1)
The first line of input contains an integer Tβ denoting the number of test cases to run. Then the test case follows.
The first line of each test case contains four space-separated integers βNβ, βMβ, βXβ, βYβ, dimensions of the room and the co-ordinate of the bomb.
The next N lines of each test cases contain M space-separated integers denoting the elements of the grid.
Output Format :
For each test case print the minimum amount of time taken by the room to spread across all the reachable cells.
Output for each test case is printed in a separate line.
Note :
You donβt need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N, M <= 500
1 <= X <= N
1 <= Y <=M
Time Limit: 1 sec
2
2 2 1 1
0 0
1 0
1 7 1 6
0 0 0 0 0 0 0
2
5
Lets denote a cell by S if it have smoke
For the first test ,
At time 0
GRID=[[S, 0],
[1, 0]]
At time 1
GRID=[[S, S],
[1, 0]]
At time 2
GRID=[[S, S],
[1, S]]
For the second test case, it will take 5 sec for the smoke to travel from (1,6) to (0,0)
2
5 5 5 5
0 0 0 0 0
1 1 1 1 0
0 0 0 0 0
0 1 1 1 1
0 0 0 0 0
5 5 3 3
0 0 0 0 0
1 1 1 1 0
0 0 0 1 0
0 1 1 1 0
0 0 0 0 0
16
16
Can we use a breadth-first search to find the Minimum time for the smoke to spread ??
We will use a breadth-first search to find the cell which is reachable from the bomb and farthest from the bomb. We will start our BFS from the location at expanding to the four adjacent cells if there are not visited so far.
For each cell, we will also maintain the smallest distance from the bomb.
The algorithm will be-
This queue stores all the unprocessed cells, we will pop a cell from the queue and try to move to an adjacent cell
Ans stores the final answer
We will try to visit all the adjacent cells if the distance of adjacent cells is infinity then this cell is not visited yet
We will add the adjacent the cell to queue
O(N*M) where βNβ, βMβ, is the dimensions of the room.
We are visiting each cell location exactly once.
O(N*M) where βNβ, βMβ, is the dimensions of the room.
Space required to store the Distance and Queue array/list.