Skip to content

Commit 2b1aef1

Browse files
committed
(#286)WallsandGates
1 parent f0cc89d commit 2b1aef1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public void wallsAndGates(int[][] rooms) {
3+
if(rooms.length <= 0 || rooms[0].length <= 0) return;
4+
Queue<int []> queue = new LinkedList<>();
5+
for(int i = 0; i < rooms.length; i++){
6+
for(int j = 0; j < rooms[0].length; j++){
7+
if(rooms[i][j] == 0)
8+
queue.add(new int[]{i, j});
9+
}
10+
}
11+
12+
while(!queue.isEmpty()){
13+
int index[] = queue.poll();
14+
int row = index[0];
15+
int col = index[1];
16+
if(row > 0 && rooms[row - 1][col] == Integer.MAX_VALUE){
17+
rooms[row - 1][col] = rooms[row][col] + 1;
18+
queue.add(new int[]{row - 1, col});
19+
}
20+
if(row < rooms.length - 1 && rooms[row + 1][col] == Integer.MAX_VALUE){
21+
rooms[row + 1][col] = rooms[row][col] + 1;
22+
queue.add(new int[]{row + 1, col});
23+
}
24+
25+
if(col > 0 && rooms[row][col - 1] == Integer.MAX_VALUE){
26+
rooms[row][col - 1] = rooms[row][col] + 1;
27+
queue.add(new int[]{row, col - 1});
28+
}
29+
if(col < rooms[0].length - 1 && rooms[row][col + 1] == Integer.MAX_VALUE){
30+
rooms[row][col + 1] = rooms[row][col] + 1;
31+
queue.add(new int[]{row, col + 1});
32+
}
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)