File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Tree Breadth First Search Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public void wallsAndGates (int [][] rooms ) {
3+ Set <int []> gates = new HashSet <>();
4+
5+ for (int row = 0 ; row < rooms .length ; row ++) {
6+ for (int col = 0 ; col < rooms [row ].length ; col ++) {
7+ if (rooms [row ][col ] == 0 ) {
8+ gates .add (new int [] { row , col });
9+ }
10+ }
11+ }
12+
13+ Queue <int []> q = new LinkedList <>();
14+
15+ for (int [] gate : gates ) {
16+ q .offer (gate );
17+ }
18+
19+ int distance = 0 ;
20+ boolean [][] visited = new boolean [rooms .length ][rooms [0 ].length ];
21+
22+ while (!q .isEmpty ()) {
23+ int size = q .size ();
24+
25+ for (int i = 0 ; i < size ; i ++) {
26+ int [] coord = q .poll ();
27+ int x = coord [0 ], y = coord [1 ];
28+
29+ if (x < 0 || y < 0 || x >= rooms .length || y >= rooms [0 ].length ||
30+ rooms [x ][y ] == -1 || visited [x ][y ]) {
31+ continue ;
32+ }
33+
34+ rooms [x ][y ] = Math .min (rooms [x ][y ], distance );
35+ visited [x ][y ] = true ;
36+
37+ q .offer (new int [] { x + 1 , y });
38+ q .offer (new int [] { x - 1 , y });
39+ q .offer (new int [] { x , y + 1 });
40+ q .offer (new int [] { x , y - 1 });
41+ }
42+
43+ ++distance ;
44+ }
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments