|
1 | 1 | /**
|
2 |
| - * DFS |
| 2 | + * Graph | DFS |
3 | 3 | * Time O(n) | Space O(n)
|
4 | 4 | * https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
|
5 | 5 | * @param {number} n
|
|
8 | 8 | * @return {number}
|
9 | 9 | */
|
10 | 10 | 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 | +}; |
13 | 15 |
|
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 | + } |
15 | 22 |
|
16 |
| - for(let i = 0; i < edges.length; i++) { |
| 23 | + if (pathLen > 0 || hasApple[curr]) return pathLen+2; |
| 24 | + return 0; |
| 25 | +} |
17 | 26 |
|
18 |
| - const parent = edges[i][0]; |
19 |
| - const child = edges[i][1]; |
| 27 | +const makeGraph = (edges) => { |
| 28 | + const graph = {}; |
20 | 29 |
|
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++) { |
28 | 31 |
|
29 |
| - tree[child].push(parent); |
30 |
| - tree[parent].push(child); |
31 |
| - } |
| 32 | + const from = edges[i][0]; |
| 33 | + const to = edges[i][1]; |
32 | 34 |
|
33 |
| - const dfs = (curr, pre) => { |
| 35 | + if (!graph[from]) { |
| 36 | + graph[from] = []; |
| 37 | + } |
34 | 38 |
|
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 | + }; |
40 | 42 |
|
41 |
| - if(pathLen > 0 || hasApple[curr]) return pathLen+2; |
42 |
| - return 0; |
| 43 | + graph[to].push(from); |
| 44 | + graph[from].push(to); |
43 | 45 | }
|
44 | 46 |
|
45 |
| - const result = dfs(0, -1) - 2; |
46 |
| - return (result > 0 && result) || 0; |
47 |
| -}; |
| 47 | + return graph; |
| 48 | +} |
0 commit comments