Skip to content

Commit add6033

Browse files
authored
Add Dijkstra's algorithm to Typescript (#291)
1 parent 1d5567f commit add6033

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { Graph, GraphIterable } from "./iterable_graph";
2+
3+
const dijkstraGraph: Graph<Graph<number>> = {
4+
start: { a: 6, b: 2 },
5+
a: { fin: 1 },
6+
b: { a: 3, fin: 5 },
7+
fin: {},
8+
};
9+
10+
const costs: Graph<number> = {
11+
a: 6,
12+
b: 2,
13+
fin: Infinity,
14+
};
15+
16+
const parents: Graph<string | null> = {
17+
a: "start",
18+
b: "start",
19+
fin: null,
20+
};
21+
22+
let processed: string[] = [];
23+
24+
const findLowestCostNode = (costs: Graph<number>): string | null => {
25+
let lowestCost = Infinity;
26+
let lowestCostNode: string | null = null;
27+
28+
const iterableGraph = new GraphIterable(costs);
29+
30+
for (const node of iterableGraph) {
31+
const cost = costs[node];
32+
if (cost < lowestCost && !processed.includes(node)) {
33+
lowestCost = cost;
34+
lowestCostNode = node;
35+
}
36+
}
37+
return lowestCostNode;
38+
};
39+
40+
let node = findLowestCostNode(costs);
41+
42+
while (node !== null) {
43+
const cost = costs[node];
44+
45+
const neighbors = dijkstraGraph[node];
46+
Object.keys(neighbors).forEach((n: string) => {
47+
const newCost = cost + neighbors[n];
48+
if (costs[n] > newCost) {
49+
costs[n] = newCost;
50+
parents[n] = node;
51+
}
52+
});
53+
54+
processed.push(node);
55+
node = findLowestCostNode(costs);
56+
}
57+
58+
console.log("Cost from the start to each node:");
59+
console.log(costs); // { a: 5, b: 2, fin: 6 }
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export interface Graph<T> {
2+
[key: string]: T;
3+
}
4+
5+
export class GraphIterable<T> implements Iterable<string> {
6+
private graph: Graph<T>;
7+
8+
constructor(graph: Graph<T>) {
9+
this.graph = graph;
10+
}
11+
12+
[Symbol.iterator](): Iterator<string> {
13+
const keys = Object.keys(this.graph);
14+
let index = 0;
15+
16+
return {
17+
next: (): IteratorResult<string> => {
18+
if (index < keys.length) {
19+
return { value: keys[index++], done: false };
20+
} else {
21+
return { value: undefined, done: true };
22+
}
23+
},
24+
};
25+
}
26+
}

0 commit comments

Comments
 (0)