Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitab123e9

Browse files
add a solution for 841
1 parenta464cde commitab123e9

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
returnfalse;
5959
}
6060
}
61+
62+
publicstaticclassSolution3 {
63+
/**
64+
* My completely original recursive solution.
65+
*/
66+
publicbooleancanVisitAllRooms(List<List<Integer>>rooms) {
67+
Set<Integer>visited =newHashSet<>();
68+
visited.add(0);
69+
Set<Integer>keys =newHashSet<>();
70+
keys.addAll(rooms.get(0));
71+
returndfs(rooms,visited,keys);
72+
}
73+
74+
privatebooleandfs(List<List<Integer>>rooms,Set<Integer>visited,Set<Integer>keys) {
75+
if (visited.size() ==rooms.size()) {
76+
returntrue;
77+
}
78+
Set<Integer>newKeys =newHashSet<>();
79+
for (intkey :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+
returntrue;
89+
}
90+
if (newKeys.size() ==0) {
91+
returnfalse;
92+
}
93+
keys.addAll(newKeys);
94+
dfs(rooms,visited,keys);
95+
returnvisited.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
publicclass_841Test {
1414
privatestatic_841.Solution1solution1;
1515
privatestatic_841.Solution2solution2;
16+
privatestatic_841.Solution3solution3;
1617
privatestaticList<List<Integer>>rooms;
1718

1819
@BeforeClass
1920
publicstaticvoidsetup() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp