Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5cf9e5d

Browse files
Create 286-Walls-and-Gates.java
1 parent fb73086 commit 5cf9e5d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

java/286-Walls-and-Gates.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//Same as rotting oranges
2+
//Time complexity will be O(N^2) since we are basically traversing every value in the grid.
3+
4+
class Solution {
5+
public void wallsAndGates(int[][] rooms) {
6+
Queue<int[]> q = new LinkedList<>();
7+
int m = rooms.length;
8+
int n = rooms[0].length;
9+
for (int i=0; i<m; i++) {
10+
for (int j=0; j<n; j++) {
11+
if (rooms[i][j]==0)
12+
q.add(new int[]{i, j});
13+
}
14+
}
15+
if (q.size()==0)
16+
return;
17+
int[][] dirs = {{-1,0}, {0,-1}, {1,0}, {0,1}};
18+
int dis = 0;
19+
while (!q.isEmpty()) {
20+
++dis;
21+
int[] cur = q.poll();
22+
int row = cur[0];
23+
int col = cur[1];
24+
for (int[] dir: dirs) {
25+
int x = row+dir[0];
26+
int y = col+dir[1];
27+
if (x>=m || y>=n || x<0 || y<0 || rooms[x][y]!=Integer.MAX_VALUE)
28+
continue;
29+
q.add(new int[]{x, y});
30+
//since cur is basically the index of door (which is equal to 0)
31+
//So, we can just grab that value (rooms[row][col]) and add 1 to it and change it every time
32+
rooms[x][y] = rooms[row][col]+1;
33+
//So, one level further from door (value 0) is equal to 1. Now, we do bfs from that position so value will be 2 and so on.
34+
}
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)