Skip to content

Commit 2c60bd1

Browse files
authored
Update 2277-closest-node-to-path-in-tree.js
1 parent 24e90ea commit 2c60bd1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

2277-closest-node-to-path-in-tree.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,54 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number[][]} query
5+
* @return {number[]}
6+
*/
7+
const closestNode = function(n, edges, query) {
8+
const g = new Map()
9+
for(const [p, q] of edges) {
10+
if(!g.has(p)) g.set(p, new Set())
11+
if(!g.has(q)) g.set(q, new Set())
12+
g.get(p).add(q)
13+
g.get(q).add(p)
14+
}
15+
const dist = Array.from({ length: n }, () => Array(n).fill(null))
16+
for(let i = 0; i < n; i++) dfs(i, i, 0)
17+
const res = []
18+
// console.log(dist)
19+
for(const [s, e, t] of query) {
20+
let tmp = Infinity, cur = s, el
21+
while(true) {
22+
if(dist[cur][t] < tmp) {
23+
tmp = dist[cur][t]
24+
el = cur
25+
}
26+
if(cur === e) break
27+
for(const nxt of (g.get(cur) || [])) {
28+
if(dist[cur][e] === dist[nxt][e] + 1) {
29+
cur = nxt
30+
break
31+
}
32+
}
33+
}
34+
res.push(el)
35+
}
36+
37+
return res
38+
39+
function dfs(root, node, d) {
40+
dist[root][node] = d
41+
for(const nxt of (g.get(node) || [])) {
42+
if(nxt !== root && dist[root][nxt] == null) {
43+
dfs(root, nxt, d + 1)
44+
}
45+
}
46+
}
47+
};
48+
49+
// another
50+
51+
152
/**
253
* @param {number} n
354
* @param {number[][]} edges

0 commit comments

Comments
 (0)