Skip to content

Commit 6fd3879

Browse files
authored
Create 2277-closest-node-to-path-in-tree.js
1 parent 7bd8125 commit 6fd3879

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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 graph = {}
9+
for (const [a, b] of edges) {
10+
if (graph[a] == null) graph[a] = []
11+
if (graph[b] == null) graph[b] = []
12+
graph[a].push(b)
13+
graph[b].push(a)
14+
}
15+
16+
const dis = Array.from({ length: n }, () => Array(n).fill(Infinity))
17+
for (let i = 0; i < n; i++) {
18+
let que = [i]
19+
dis[i][i] = 0
20+
while (que.length) {
21+
const tmp = []
22+
for (const q of que) {
23+
for (const nxt of graph[q] || []) {
24+
if (dis[i][nxt] === Infinity) {
25+
dis[i][nxt] = dis[i][q] + 1
26+
tmp.push(nxt)
27+
}
28+
}
29+
}
30+
que = tmp
31+
}
32+
}
33+
34+
const arr = []
35+
36+
for (const [a, b, q] of query) {
37+
let tmp = Infinity, res = -1
38+
for (let idx = 0; idx < n; idx++) {
39+
const d= dis[idx][a] + dis[idx][b] + dis[idx][q]
40+
if(d < tmp) {
41+
tmp = d
42+
res = idx
43+
}
44+
}
45+
arr.push(res)
46+
}
47+
return arr
48+
}

0 commit comments

Comments
 (0)