Skip to content

Commit 5a10480

Browse files
committed
Renames, initialize distances to Infinity, remove external link
1 parent 06298f1 commit 5a10480

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

graph/dijkstra.ts

+7-7
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
*/
1212
export const dijkstra = (graph: number[][], start: number): number[] => {
1313
let visited = Array(graph.length).fill(false);
14-
let paths = Array(graph.length).fill(Number.MAX_SAFE_INTEGER);
15-
paths[start] = 0;
14+
let distances = Array(graph.length).fill(Infinity);
15+
distances[start] = 0;
1616

1717
let node = start;
1818
while (node !== -1) {
@@ -21,15 +21,15 @@ export const dijkstra = (graph: number[][], start: number): number[] => {
2121
if (child == node || weight === 0) {
2222
return;
2323
}
24-
let new_path = paths[node] + weight;
25-
if (new_path < paths[child]) {
26-
paths[child] = new_path;
24+
let new_path = distances[node] + weight;
25+
if (new_path < distances[child]) {
26+
distances[child] = new_path;
2727
}
2828
});
29-
node = extract_min(paths, visited);
29+
node = extract_min(distances, visited);
3030
}
3131

32-
return paths;
32+
return distances;
3333
}
3434

3535
const extract_min = (paths: number[], visited: boolean[]): number => {

graph/test/dijkstra.test.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ describe("dijkstra", () => {
1616
}
1717

1818
it("should return the correct value", () => {
19-
// Example from https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
2019
let graph = init_graph(9);
2120
add_edge(graph, 0, 1, 4);
2221
add_edge(graph, 0, 7, 8);
@@ -54,8 +53,7 @@ describe("dijkstra", () => {
5453

5554
let unreachable_graph = init_graph(3);
5655
add_edge(unreachable_graph, 0, 1, 1);
57-
const m = Number.MAX_SAFE_INTEGER
58-
test.each([[0, [0, 1, m]], [1, [1, 0, m]], [2, [m, m, 0]]])(
56+
test.each([[0, [0, 1, Infinity]], [1, [1, 0, Infinity]], [2, [Infinity, Infinity, 0]]])(
5957
"correct result for graph with unreachable nodes with source node %i",
6058
(source, result) => {
6159
expect(dijkstra(unreachable_graph, source)).toStrictEqual(result);

0 commit comments

Comments
 (0)