Skip to content

Commit c9618c0

Browse files
add a solution for 841
1 parent 2793ac5 commit c9618c0

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
import java.util.List;
66
import java.util.Queue;
77
import java.util.Set;
8+
import java.util.TreeSet;
89

910
public 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
}

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
public 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
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy