-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-064-longestPath-2.js
133 lines (104 loc) · 2.56 KB
/
structy-064-longestPath-2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// p: graph
// r: num
// a -> c
// | /
// b
//
//
// q -> r -> s
// |\ |
// v v v
// u <- t
// bfs iterative O(edges) O(nodes)
const longestPath = (graph) => {
let max = -Infinity;
for (let node in graph) {
const stack = [[node, 0]];
while (stack.length > 0) {
const [current, distance] = stack.shift();
max = Math.max(distance, max);
for (let nei of graph[current]) {
graph[current].length > 0 && stack.push([nei, distance + 1]);
}
}
}
return max;
};
// dfs recursive O(edges) O(nodes)
// const longestPath = (graph) => {
// const distance = {};
// for (let node in graph) {
// graph[node].length === 0 && (distance[node] = 0);
// }
// for (let node in graph) {
// explore(graph, node, distance);
// }
// return Math.max(...Object.values(distance));
// };
// const explore = (graph, node, distance) => {
// if (node in distance) return distance[node];
// let max = -Infinity;
// for (let nei of graph[node]) {
// max = Math.max(max, explore(graph, nei, distance));
// }
// distance[node] = max + 1;
// return max + 1;
// };
//////////////////////////////////////////////////////////////
// const longestPath = (graph) => {
// const distance = {};
// for (let node in graph) {
// graph[node].length === 0 && (distance[node] = 0);
// }
// for (let node in graph) {
// explore(graph, node, distance);
// }
// // let max = -Infinity;
// // for (let node in distance) {
// // max = Math.max(max, distance[node]);
// // }
// // return max;
// return Math.max(...Object.values(distance));
// };
// const explore = (graph, node, distance) => {
// if (node in distance) return distance[node];
// let max = -Infinity;
// for (let nei of graph[node]) {
// max = Math.max(max, explore(graph, nei, distance));
// }
// distance[node] = max + 1;
// return max + 1;
// };
// // WRONG
// const longestPath = (graph) => {
// let max = -Infinity;
// for (let node in graph) {
// console.log(node, explore(graph, node));
// max = Math.max(max, explore(graph, node));
// }
// return max;
// };
// const explore = (graph, node) => {
// if (graph[node].length === 0) return 1;
// let count = 0;
// for (let nei of graph[node]) {
// count += explore(graph, nei);
// }
// return count;
// };
// const graph = {
// a: ["c", "b"],
// b: ["c"],
// c: [],
// };
const graph = {
a: ["c", "b"],
b: ["c"],
c: [],
q: ["r"],
r: ["s", "u", "t"],
s: ["t"],
t: ["u"],
u: [],
};
console.log(longestPath(graph));