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

Commitc9618c0

Browse files
add a solution for 841
1 parent2793ac5 commitc9618c0

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
importjava.util.List;
66
importjava.util.Queue;
77
importjava.util.Set;
8+
importjava.util.TreeSet;
89

910
publicclass_841 {
1011
publicstaticclassSolution1 {
@@ -34,4 +35,27 @@ public boolean canVisitAllRooms(List<List<Integer>> rooms) {
3435
returnunvisitedRooms.isEmpty();
3536
}
3637
}
38+
39+
publicstaticclassSolution2 {
40+
publicbooleancanVisitAllRooms(List<List<Integer>>rooms) {
41+
TreeSet<Integer>treeSet =newTreeSet<>();
42+
Set<Integer>visited =newHashSet<>();
43+
visited.add(0);
44+
treeSet.addAll(rooms.get(0));
45+
while (!treeSet.isEmpty()) {
46+
Integerkey =treeSet.pollFirst();
47+
if (!visited.add(key)) {
48+
continue;
49+
}
50+
if (visited.size() ==rooms.size()) {
51+
returntrue;
52+
}
53+
treeSet.addAll(rooms.get(key));
54+
}
55+
if (visited.size() ==rooms.size()) {
56+
returntrue;
57+
}
58+
returnfalse;
59+
}
60+
}
3761
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212

1313
publicclass_841Test {
1414
privatestatic_841.Solution1solution1;
15+
privatestatic_841.Solution2solution2;
1516
privatestaticList<List<Integer>>rooms;
1617

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp