-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.ts
43 lines (39 loc) · 1.23 KB
/
Solution.ts
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
class Graph {
private g: number[][] = [];
private inf: number = 1 << 29;
constructor(n: number, edges: number[][]) {
this.g = Array.from({ length: n }, () => Array(n).fill(this.inf));
for (const [f, t, c] of edges) {
this.g[f][t] = c;
}
}
addEdge(edge: number[]): void {
const [f, t, c] = edge;
this.g[f][t] = c;
}
shortestPath(node1: number, node2: number): number {
const n = this.g.length;
const dist: number[] = new Array(n).fill(this.inf);
dist[node1] = 0;
const vis: boolean[] = new Array(n).fill(false);
for (let i = 0; i < n; ++i) {
let t = -1;
for (let j = 0; j < n; ++j) {
if (!vis[j] && (t === -1 || dist[j] < dist[t])) {
t = j;
}
}
vis[t] = true;
for (let j = 0; j < n; ++j) {
dist[j] = Math.min(dist[j], dist[t] + this.g[t][j]);
}
}
return dist[node2] >= this.inf ? -1 : dist[node2];
}
}
/**
* Your Graph object will be instantiated and called as such:
* var obj = new Graph(n, edges)
* obj.addEdge(edge)
* var param_2 = obj.shortestPath(node1,node2)
*/