Skip to content

Commit 52c4ab6

Browse files
authoredOct 18, 2024
Update with graph approach. Add spaces after control flow statements.
1 parent d3faab0 commit 52c4ab6

File tree

1 file changed

+29
-28
lines changed

1 file changed

+29
-28
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* DFS
2+
* Graph | DFS
33
* Time O(n) | Space O(n)
44
* https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
55
* @param {number} n
@@ -8,40 +8,41 @@
88
* @return {number}
99
*/
1010
var minTime = function(n, edges, hasApple) {
11-
12-
if(n === 1) return 0;
11+
if (n === 1) return 0;
12+
const result = dfs(0, -1, makeGraph(edges), hasApple) - 2;
13+
return (result > 0 && result) || 0;
14+
};
1315

14-
const tree = {};
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+
}
1522

16-
for(let i = 0; i < edges.length; i++) {
23+
if (pathLen > 0 || hasApple[curr]) return pathLen+2;
24+
return 0;
25+
}
1726

18-
const parent = edges[i][0];
19-
const child = edges[i][1];
27+
const makeGraph = (edges) => {
28+
const graph = {};
2029

21-
if(!tree[parent]) {
22-
tree[parent] = [];
23-
}
24-
25-
if(!tree[child]) {
26-
tree[child] = [];
27-
};
30+
for (let i = 0; i < edges.length; i++) {
2831

29-
tree[child].push(parent);
30-
tree[parent].push(child);
31-
}
32+
const from = edges[i][0];
33+
const to = edges[i][1];
3234

33-
const dfs = (curr, pre) => {
35+
if (!graph[from]) {
36+
graph[from] = [];
37+
}
3438

35-
let pathLen = 0;
36-
for(const nextNode of tree[curr]) {
37-
if(nextNode === pre) continue;
38-
pathLen += dfs(nextNode, curr);
39-
}
39+
if (!graph[to]) {
40+
graph[to] = [];
41+
};
4042

41-
if(pathLen > 0 || hasApple[curr]) return pathLen+2;
42-
return 0;
43+
graph[to].push(from);
44+
graph[from].push(to);
4345
}
4446

45-
const result = dfs(0, -1) - 2;
46-
return (result > 0 && result) || 0;
47-
};
47+
return graph;
48+
}

0 commit comments

Comments
 (0)
Please sign in to comment.