Skip to content

Commit 11916e0

Browse files
authored
Merge pull request #3589 from aadil42/patch-115
Create 1443-minimum-time-to-collect-all-apples-in-a-tree.js
2 parents f37d9d0 + 8637c07 commit 11916e0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Graph | DFS
3+
* Time O(n) | Space O(n)
4+
* https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
5+
* @param {number} n
6+
* @param {number[][]} edges
7+
* @param {boolean[]} hasApple
8+
* @return {number}
9+
*/
10+
var minTime = function(n, edges, hasApple) {
11+
if (n === 1) return 0;
12+
const result = dfs(0, -1, makeGraph(edges), hasApple) - 2;
13+
return (result > 0 && result) || 0;
14+
};
15+
16+
const dfs = (curr, pre, graph, hasApple) => {
17+
let pathLen = 0;
18+
for (const nextNode of graph[curr]) {
19+
if (nextNode === pre) continue;
20+
pathLen += dfs(nextNode, curr, graph, hasApple);
21+
}
22+
23+
if (pathLen > 0 || hasApple[curr]) return pathLen + 2;
24+
return 0;
25+
}
26+
27+
const makeGraph = (edges) => {
28+
const graph = {};
29+
30+
for (let i = 0; i < edges.length; i++) {
31+
32+
const from = edges[i][0];
33+
const to = edges[i][1];
34+
35+
if (!graph[from]) {
36+
graph[from] = [];
37+
}
38+
39+
if (!graph[to]) {
40+
graph[to] = [];
41+
};
42+
43+
graph[to].push(from);
44+
graph[from].push(to);
45+
}
46+
47+
return graph;
48+
}

0 commit comments

Comments
 (0)