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

Commit c04d70e

Browse files
committed
Solve 1443. Minimum Time to Collect All Apples in a Tree
1 parent d216d77 commit c04d70e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
3+
private fun dfs(
4+
n: Int,
5+
neighbours: Array<MutableList<Int>>,
6+
hasApple: List<Boolean>,
7+
visited: MutableSet<Int>
8+
): Int {
9+
if (visited.contains(n)) return 0
10+
var time = 0
11+
12+
visited.add(n)
13+
neighbours[n].forEach { neighbour ->
14+
time += dfs(neighbour, neighbours, hasApple, visited)
15+
}
16+
17+
if (n != 0 && (time > 0 || hasApple[n])) {
18+
time += 2
19+
}
20+
21+
return time
22+
}
23+
24+
fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>): Int {
25+
if (hasApple.none { it }) return 0
26+
27+
val neighbours = Array(n) { mutableListOf<Int>() }
28+
val visited = mutableSetOf<Int>()
29+
30+
edges.forEach { edge ->
31+
neighbours[edge[0]].add(edge[1])
32+
neighbours[edge[1]].add(edge[0])
33+
}
34+
35+
return dfs(0, neighbours, hasApple, visited)
36+
}
37+
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /