Skip to content

Commit 057ee23

Browse files
walls and gates using two BFS solutions
1 parent 1a49726 commit 057ee23

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

MEDIUM/src/medium/WallsAndGates.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package medium;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Created by fishercoder1534 on 9/30/16.
7+
*/
8+
public class WallsAndGates {
9+
class BFS_solution_without_queue{
10+
11+
int[] dirs = new int[]{0,1,0,-1,0};
12+
public void wallsAndGates(int[][] rooms) {
13+
if(rooms == null || rooms.length == 0 || rooms[0].length == 0) return;
14+
int m = rooms.length, n = rooms[0].length;
15+
for(int i = 0; i < m; i++){
16+
for(int j = 0; j < n; j++){
17+
if(rooms[i][j] == 0) bfs(rooms, i, j, m, n);
18+
}
19+
}
20+
}
21+
22+
void bfs(int[][] rooms, int i, int j, int m, int n){
23+
for(int k = 0; k < 4; k++){
24+
int x = dirs[k]+i;
25+
int y = dirs[k+1]+j;
26+
if(x >= 0 && y >= 0 && x < m && y < n && rooms[x][y] > rooms[i][j]+1) {
27+
rooms[x][y] = rooms[i][j]+1;
28+
bfs(rooms, x, y, m, n);
29+
}
30+
}
31+
}
32+
33+
}
34+
35+
class BFS_solution_with_a_queue{
36+
37+
//push all gates into the queue first, and then put all its neighbours into the queue with one distance to the gate, then continue to push the rest of the nodes into the queue, and put all their neighbours into the queue with the nodes' value plus one until the queue is empty
38+
int[] dirs = new int[]{0,1,0,-1,0};
39+
public void wallsAndGates(int[][] rooms) {
40+
if(rooms == null || rooms.length == 0 || rooms[0].length == 0) return;
41+
int m = rooms.length, n = rooms[0].length;
42+
Queue<int[]> queue = new LinkedList();
43+
for(int i = 0; i < m; i++){
44+
for(int j = 0; j < n; j++){
45+
if(rooms[i][j] == 0) queue.offer(new int[]{i,j});
46+
}
47+
}
48+
49+
while(!queue.isEmpty()){
50+
int[] curr = queue.poll();
51+
for(int k = 0; k < 4; k++){
52+
int x = curr[0]+dirs[k];
53+
int y = curr[1]+dirs[k+1];
54+
if(x >= 0 && x < m && y >= 0 && y < n && rooms[x][y] == Integer.MAX_VALUE) {
55+
rooms[x][y] = rooms[curr[0]][curr[1]]+1;
56+
queue.offer(new int[]{x,y});
57+
}
58+
}
59+
}
60+
}
61+
62+
}
63+
}

0 commit comments

Comments
 (0)