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
Links: http://leetcode.com/problems/walls-and-gates/
Exercises
Find the shortest distance between the space and gate in the matrix. Here we can use BFS, first put all the gate into the queue, and then according to the gate calculation up and down, if there is room, then the room added to the queue.
Time Complexity-o (4n), Space complexity-o (4n)
Public classSolution { Public voidWallsandgates (int[] rooms) { if(Rooms = =NULL|| Rooms.length = = 0) { return; } Queue<int[]> queue =NewLinkedlist<>(); for(inti = 0; i < rooms.length; i++) { for(intj = 0; J < Rooms[0].length; J + +) { if(Rooms[i][j] = = 0) {Queue.add (New int[]{i, J}]; } } } while(!Queue.isempty ()) { int[] Gate =Queue.poll (); introw = Gate[0], col = gate[1]; if(Row > 0 && rooms[row-1][col] = =integer.max_value) {Rooms[row-1][col] = Rooms[row][col] + 1; Queue.add (New int[]{row-1, col}); } if(Row < rooms.length-1 && Rooms[row + 1][col] = =integer.max_value) {Rooms[row+ 1][col] = Rooms[row][col] + 1; Queue.add (New int[]{row + 1, col}); } if(Col > 0 && rooms[row][col-1] = =integer.max_value) {Rooms[row][col-1] = Rooms[row][col] + 1; Queue.add (New int[]{row, Col-1}); } if(Col < rooms[0].length-1 && Rooms[row][col + 1] = =integer.max_value) {Rooms[row][col+ 1] = Rooms[row][col] + 1; Queue.add (New int[]{row, col + 1}); } } }}
Reference:
Https://www.cs.ubc.ca/~kevinlb/teaching/cs322%20-%202008-9/Lectures/Search3.pdf
Https://en.wikipedia.org/wiki/Breadth-first_search#Time_and_space_complexity
Https://leetcode.com/discuss/60552/beautiful-java-solution-10-lines
Https://leetcode.com/discuss/60418/c-bfs-clean-solution-with-simple-explanations
Https://leetcode.com/discuss/60170/6-lines-o-mn-python-bfs
Https://leetcode.com/discuss/73686/concise-java-solution-bfs-7ms
Https://leetcode.com/discuss/68456/java-dfs-solution-much-quicker-and-simpler-than-bfs
286.Walls and Gates