Skip to content

Commit 2045bb5

Browse files
committed
841. Keys and Rooms
1 parent c0056e8 commit 2045bb5

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
object Solution {
2+
def dfs(graph: Map[Int, List[Int]], start: Int, visited: Set[Int] = Set()): Set[Int] = {
3+
if (visited.contains(start)) visited
4+
else graph.getOrElse(start, Nil).foldLeft(visited + start)(
5+
(acc, neighbor) => dfs(graph, neighbor, acc)
6+
)
7+
}
8+
9+
def canVisitAllRooms(rooms: List[List[Int]]): Boolean = {
10+
val graph = rooms.zipWithIndex.map(r => r._2 -> r._1).toMap
11+
val visited = dfs(graph, 0)
12+
visited.size == graph.size
13+
}
14+
}
15+
16+
Solution.canVisitAllRooms(List(List(1), List(2), List(3), Nil))
17+
Solution.canVisitAllRooms(List(List(1, 3), List(3, 0, 1), List(2), List(0)))

0 commit comments

Comments
 (0)