Skip to content

Improve dijkstra visualization #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 28, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions algorithm/graph_search/dijkstra/shortest_path/code.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
function Dijkstra(start, end) {
var MAX_VALUE = Infinity;
var minIndex, minDistance;
var S = []; // S[i] returns the distance from node v to node start
var D = []; // D[i] indicates whether the i-th node is discovered or not
for (var i = 0; i < G.length; i++) {
D.push(false);
S[i] = MAX_VALUE;
}
for (var i = 0; i < G.length; i++) D.push(false);
S[start] = 0; // Starting node is at distance 0 from itself
var k = G.length;
while (k--) {
// Finding a node with the shortest distance from S[minIndex]
minDistance = MAX_VALUE;
for (i = 0; i < G.length; i++) {
tracerS._select(i)._wait();
if (S[i] < minDistance && !D[i]) {
minDistance = S[i];
minIndex = i;
}
tracerS._deselect(i);
}
if (minDistance == MAX_VALUE) break; // If there is no edge from current node, jump out of loop
D[minIndex] = true;
tracerS._notify(minIndex, S[minIndex])._denotify(minIndex);
tracer._visit(minIndex)._wait();
// For every unvisited neighbour of current node, we check
// whether the path to it is shorter if going over the current node
for (i = 0; i < G.length; i++) {
if (G[minIndex][i] && S[i] > S[minIndex] + G[minIndex][i]) {
S[i] = S[minIndex] + G[minIndex][i];
tracer._visit(i, minIndex, S[i])._wait();
tracer._leave(i, minIndex, S[i])._wait();
tracerS._notify(i, S[i])._wait()._denotify(i);
tracer._visit(i, minIndex, S[i])._wait()._leave(i, minIndex);
}
}
tracer._leave(minIndex)._wait();
Expand Down
14 changes: 6 additions & 8 deletions algorithm/graph_search/dijkstra/shortest_path/data.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
var tracer = new WeightedDirectedGraphTracer();
var tracerS = new Array1DTracer();
var logger = new LogTracer();
tracer.attach(logger);
/*var G = [ // G[i][j] indicates the weight of the path from the i-th node to the j-th node
[0, 3, 0, 1, 0],
[5, 0, 1, 2, 4],
[1, 0, 0, 2, 0],
[0, 2, 0, 0, 1],
[0, 1, 3, 0, 0]
];*/
var G = WeightedDirectedGraph.random(10, .4, 1, 9);
tracer._setData(G);
tracer._setData(G);
var MAX_VALUE = Infinity;
var S = []; // S[end] returns the distance from start node to end node
for (var i = 0; i < G.length; i++) S[i] = MAX_VALUE;
tracerS._setData(S);