File tree 2 files changed +28
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change 5
5
import java .util .List ;
6
6
import java .util .Queue ;
7
7
import java .util .Set ;
8
+ import java .util .TreeSet ;
8
9
9
10
public class _841 {
10
11
public static class Solution1 {
@@ -34,4 +35,27 @@ public boolean canVisitAllRooms(List<List<Integer>> rooms) {
34
35
return unvisitedRooms .isEmpty ();
35
36
}
36
37
}
38
+
39
+ public static class Solution2 {
40
+ public boolean canVisitAllRooms (List <List <Integer >> rooms ) {
41
+ TreeSet <Integer > treeSet = new TreeSet <>();
42
+ Set <Integer > visited = new HashSet <>();
43
+ visited .add (0 );
44
+ treeSet .addAll (rooms .get (0 ));
45
+ while (!treeSet .isEmpty ()) {
46
+ Integer key = treeSet .pollFirst ();
47
+ if (!visited .add (key )) {
48
+ continue ;
49
+ }
50
+ if (visited .size () == rooms .size ()) {
51
+ return true ;
52
+ }
53
+ treeSet .addAll (rooms .get (key ));
54
+ }
55
+ if (visited .size () == rooms .size ()) {
56
+ return true ;
57
+ }
58
+ return false ;
59
+ }
60
+ }
37
61
}
Original file line number Diff line number Diff line change 12
12
13
13
public class _841Test {
14
14
private static _841 .Solution1 solution1 ;
15
+ private static _841 .Solution2 solution2 ;
15
16
private static List <List <Integer >> rooms ;
16
17
17
18
@ BeforeClass
18
19
public static void setup () {
19
20
solution1 = new _841 .Solution1 ();
21
+ solution2 = new _841 .Solution2 ();
20
22
}
21
23
22
24
@ Test
@@ -27,6 +29,7 @@ public void test1() {
27
29
rooms .add (Arrays .asList (3 ));
28
30
rooms .add (Arrays .asList ());
29
31
assertEquals (true , solution1 .canVisitAllRooms (rooms ));
32
+ assertEquals (true , solution2 .canVisitAllRooms (rooms ));
30
33
}
31
34
32
35
@ Test
@@ -37,5 +40,6 @@ public void test2() {
37
40
rooms .add (Arrays .asList (2 ));
38
41
rooms .add (Arrays .asList (0 ));
39
42
assertEquals (false , solution1 .canVisitAllRooms (rooms ));
43
+ assertEquals (false , solution2 .canVisitAllRooms (rooms ));
40
44
}
41
45
}
You can’t perform that action at this time.
0 commit comments