The original title link is here: https://leetcode.com/problems/walls-and-gates/
Topic:
You is given a m x n 2D grid initialized with these three possible values.
-1-A wall or an obstacle.
0-Gate A.
INF-Infinity means a empty room. We use the value of represent as assume that the 231 - 1 = 2147483647 distance to INF a gate are less than 2147483647 .
Fill each empty and the distance to its nearest gate. If It is the impossible to reach a gate, it should are filled with INF .
For example, given the 2D grid:
INF -1 0 infinf inf inf -1inf -1 inf -1 0 -1 inf INF
After running your function, the 2D grid should is:
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
Exercises
BFS, first add all the gate to the Que. For each gate from the que poll out, see whether there are rooms in four directions, if so, the value of the rooms to correct gate + 1, put back into the Que.
Time Complexity:o (m*n). m = rooms.length, n = rooms[0].length. Each point is not scanned more than two times. Space:o (m*n).
AC Java:
1 Public classSolution {2 Public voidWallsandgates (int[] rooms) {3 if(Rooms = =NULL|| Rooms.length = = 0 | | Rooms[0].length = = 0){4 return;5 }6 int[] Fourdire = {{0,1},{0,-1},{1,0},{-1,0}};7linkedlist<int[]> que =Newlinkedlist<int[]>();8 9 for(inti = 0; i<rooms.length; i++){Ten for(intj = 0; j<rooms[0].length; J + +){ One if(Rooms[i][j] = = 0){ AQue.add (New int[]{i,j}]; - } - } the } - - while(!Que.isempty ()) { - int[] Gate =Que.poll (); + intx = gate[0]; - inty = gate[1]; + for(intk = 0; k<4; k++){ A intNEWX = x + fourdire[k][0]; at intNewy = y + fourdire[k][1]; - if(newx>=0 && newx<rooms.length && newy>=0 && newy<rooms[0].length) { - if(Rooms[newx][newy] = =integer.max_value) { -Rooms[newx][newy] = Rooms[x][y] + 1; -Que.add (New int[]{newx, Newy}]; - } in } - } to } + } -}
Leetcode Walls and Gates