File tree Expand file tree Collapse file tree 2 files changed +28
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change 55import java .util .List ;
66import java .util .Queue ;
77import java .util .Set ;
8+ import java .util .TreeSet ;
89
910public class _841 {
1011 public static class Solution1 {
@@ -34,4 +35,27 @@ public boolean canVisitAllRooms(List<List<Integer>> rooms) {
3435 return unvisitedRooms .isEmpty ();
3536 }
3637 }
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+ }
3761}
Original file line number Diff line number Diff line change 1212
1313public class _841Test {
1414 private static _841 .Solution1 solution1 ;
15+ private static _841 .Solution2 solution2 ;
1516 private static List <List <Integer >> rooms ;
1617
1718 @ BeforeClass
1819 public static void setup () {
1920 solution1 = new _841 .Solution1 ();
21+ solution2 = new _841 .Solution2 ();
2022 }
2123
2224 @ Test
@@ -27,6 +29,7 @@ public void test1() {
2729 rooms .add (Arrays .asList (3 ));
2830 rooms .add (Arrays .asList ());
2931 assertEquals (true , solution1 .canVisitAllRooms (rooms ));
32+ assertEquals (true , solution2 .canVisitAllRooms (rooms ));
3033 }
3134
3235 @ Test
@@ -37,5 +40,6 @@ public void test2() {
3740 rooms .add (Arrays .asList (2 ));
3841 rooms .add (Arrays .asList (0 ));
3942 assertEquals (false , solution1 .canVisitAllRooms (rooms ));
43+ assertEquals (false , solution2 .canVisitAllRooms (rooms ));
4044 }
4145}
You can’t perform that action at this time.
0 commit comments