Skip to content

Commit a20fe32

Browse files
committed
Improve dijkstra visualization
1 parent b90f367 commit a20fe32

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

algorithm/graph_search/dijkstra/shortest_path/code.js

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,31 @@
11
function Dijkstra(start, end) {
2-
var MAX_VALUE = Infinity;
32
var minIndex, minDistance;
4-
var S = []; // S[i] returns the distance from node v to node start
53
var D = []; // D[i] indicates whether the i-th node is discovered or not
6-
for (var i = 0; i < G.length; i++) {
7-
D.push(false);
8-
S[i] = MAX_VALUE;
9-
}
4+
for (var i = 0; i < G.length; i++) D.push(false);
105
S[start] = 0; // Starting node is at distance 0 from itself
116
var k = G.length;
127
while (k--) {
138
// Finding a node with the shortest distance from S[minIndex]
149
minDistance = MAX_VALUE;
1510
for (i = 0; i < G.length; i++) {
11+
tracerS._select(i)._wait();
1612
if (S[i] < minDistance && !D[i]) {
1713
minDistance = S[i];
1814
minIndex = i;
1915
}
16+
tracerS._deselect(i);
2017
}
2118
if (minDistance == MAX_VALUE) break; // If there is no edge from current node, jump out of loop
2219
D[minIndex] = true;
20+
tracerS._notify(minIndex, S[minIndex])._denotify(minIndex);
2321
tracer._visit(minIndex)._wait();
2422
// For every unvisited neighbour of current node, we check
2523
// whether the path to it is shorter if going over the current node
2624
for (i = 0; i < G.length; i++) {
2725
if (G[minIndex][i] && S[i] > S[minIndex] + G[minIndex][i]) {
2826
S[i] = S[minIndex] + G[minIndex][i];
29-
tracer._visit(i, minIndex, S[i])._wait();
30-
tracer._leave(i, minIndex, S[i])._wait();
27+
tracerS._notify(i, S[i])._wait()._denotify(i);
28+
tracer._visit(i, minIndex, S[i])._wait()._leave(i, minIndex);
3129
}
3230
}
3331
tracer._leave(minIndex)._wait();
Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
var tracer = new WeightedDirectedGraphTracer();
2+
var tracerS = new Array1DTracer();
23
var logger = new LogTracer();
34
tracer.attach(logger);
4-
/*var G = [ // G[i][j] indicates the weight of the path from the i-th node to the j-th node
5-
[0, 3, 0, 1, 0],
6-
[5, 0, 1, 2, 4],
7-
[1, 0, 0, 2, 0],
8-
[0, 2, 0, 0, 1],
9-
[0, 1, 3, 0, 0]
10-
];*/
115
var G = WeightedDirectedGraph.random(10, .4, 1, 9);
12-
tracer._setData(G);
6+
tracer._setData(G);
7+
var MAX_VALUE = Infinity;
8+
var S = []; // S[end] returns the distance from start node to end node
9+
for (var i = 0; i < G.length; i++) S[i] = MAX_VALUE;
10+
tracerS._setData(S);

0 commit comments

Comments
 (0)