File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -58,4 +58,41 @@ public boolean canVisitAllRooms(List<List<Integer>> rooms) {
58
58
return false ;
59
59
}
60
60
}
61
+
62
+ public static class Solution3 {
63
+ /**
64
+ * My completely original recursive solution.
65
+ */
66
+ public boolean canVisitAllRooms (List <List <Integer >> rooms ) {
67
+ Set <Integer > visited = new HashSet <>();
68
+ visited .add (0 );
69
+ Set <Integer > keys = new HashSet <>();
70
+ keys .addAll (rooms .get (0 ));
71
+ return dfs (rooms , visited , keys );
72
+ }
73
+
74
+ private boolean dfs (List <List <Integer >> rooms , Set <Integer > visited , Set <Integer > keys ) {
75
+ if (visited .size () == rooms .size ()) {
76
+ return true ;
77
+ }
78
+ Set <Integer > newKeys = new HashSet <>();
79
+ for (int key : keys ) {
80
+ if (!visited .contains (key )) {
81
+ visited .add (key );
82
+ if (!rooms .get (key ).isEmpty ()) {
83
+ newKeys .addAll (rooms .get (key ));
84
+ }
85
+ }
86
+ }
87
+ if (visited .size () == rooms .size ()) {
88
+ return true ;
89
+ }
90
+ if (newKeys .size () == 0 ) {
91
+ return false ;
92
+ }
93
+ keys .addAll (newKeys );
94
+ dfs (rooms , visited , keys );
95
+ return visited .size () == rooms .size ();
96
+ }
97
+ }
61
98
}
Original file line number Diff line number Diff line change 13
13
public class _841Test {
14
14
private static _841 .Solution1 solution1 ;
15
15
private static _841 .Solution2 solution2 ;
16
+ private static _841 .Solution3 solution3 ;
16
17
private static List <List <Integer >> rooms ;
17
18
18
19
@ BeforeClass
19
20
public static void setup () {
20
21
solution1 = new _841 .Solution1 ();
21
22
solution2 = new _841 .Solution2 ();
23
+ solution3 = new _841 .Solution3 ();
22
24
}
23
25
24
26
@ Test
@@ -30,6 +32,7 @@ public void test1() {
30
32
rooms .add (Arrays .asList ());
31
33
assertEquals (true , solution1 .canVisitAllRooms (rooms ));
32
34
assertEquals (true , solution2 .canVisitAllRooms (rooms ));
35
+ assertEquals (true , solution3 .canVisitAllRooms (rooms ));
33
36
}
34
37
35
38
@ Test
@@ -41,5 +44,6 @@ public void test2() {
41
44
rooms .add (Arrays .asList (0 ));
42
45
assertEquals (false , solution1 .canVisitAllRooms (rooms ));
43
46
assertEquals (false , solution2 .canVisitAllRooms (rooms ));
47
+ assertEquals (false , solution3 .canVisitAllRooms (rooms ));
44
48
}
45
49
}
You can’t perform that action at this time.
0 commit comments