-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (48 loc) · 1.39 KB
/
index.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
/**
* Shortest path fast algorithm
*
* @author David Lacedonia <[email protected]>
*
* @param {number} edges
* @param {number[][]} points
* @param {number} dst
*
* @return {number} shortest distance
*/
/**
* @param {number} n
* @param {number[][]} flights
* @param {number} src
* @param {number} dst
* @param {number} k
* @return {number}
*/
var shortestPathFastAlgorithm = function (n, flights, dst) {
let output = Number.MAX_SAFE_INTEGER;
let graph = {};
let vertexs = new Array(n).fill(Infinity);
let queue = [0];
let visited = { 0: true };
vertexs[0] = 0;
for (let flight of flights) {
const [origin, target, distance] = flight;
graph[origin] = [...(graph[origin] || []), { target, distance }];
}
while (queue.length) {
const curr = queue.shift();
visited[curr] = false;
for (let neighbour of graph[curr] || []) {
const { target, distance } = neighbour;
const totalDistance = distance + vertexs[curr];
if (visited[target]) continue;
if (vertexs[target] > totalDistance) {
vertexs[target] = totalDistance;
queue.push(target);
visited[target] = true;
}
}
}
output = vertexs[dst];
return output === Number.MAX_SAFE_INTEGER ? -1 : output;
};
export default shortestPathFastAlgorithm;