Skip to content

Commit ab123e9

Browse files
add a solution for 841
1 parent a464cde commit ab123e9

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/main/java/com/fishercoder/solutions/_841.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,41 @@ public boolean canVisitAllRooms(List<List<Integer>> rooms) {
5858
return false;
5959
}
6060
}
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+
}
6198
}

src/test/java/com/fishercoder/_841Test.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,14 @@
1313
public class _841Test {
1414
private static _841.Solution1 solution1;
1515
private static _841.Solution2 solution2;
16+
private static _841.Solution3 solution3;
1617
private static List<List<Integer>> rooms;
1718

1819
@BeforeClass
1920
public static void setup() {
2021
solution1 = new _841.Solution1();
2122
solution2 = new _841.Solution2();
23+
solution3 = new _841.Solution3();
2224
}
2325

2426
@Test
@@ -30,6 +32,7 @@ public void test1() {
3032
rooms.add(Arrays.asList());
3133
assertEquals(true, solution1.canVisitAllRooms(rooms));
3234
assertEquals(true, solution2.canVisitAllRooms(rooms));
35+
assertEquals(true, solution3.canVisitAllRooms(rooms));
3336
}
3437

3538
@Test
@@ -41,5 +44,6 @@ public void test2() {
4144
rooms.add(Arrays.asList(0));
4245
assertEquals(false, solution1.canVisitAllRooms(rooms));
4346
assertEquals(false, solution2.canVisitAllRooms(rooms));
47+
assertEquals(false, solution3.canVisitAllRooms(rooms));
4448
}
4549
}

0 commit comments

Comments
 (0)