Anonymous user
Dijkstra's algorithm: Difference between revisions
D entry: the graph is now directed
m (→{{header|PHP}}: fix array minimum finder) |
(D entry: the graph is now directed) |
||
Line 381:
=={{header|D}}==
{{trans|C++}}
The algorithm and the important data structures are essentially the same as in the C++ version, so the same comments apply (built-in D associative arrays are unsorted).
<lang d>import std.stdio, std.typecons, std.algorithm, std.container;
alias
alias
const struct Neighbor {
Line 394 ⟶ 393:
}
alias AdjacencyMap = Neighbor[][Vertex]
Tuple!(Weight[Vertex], Vertex[Vertex])
Line 403 ⟶ 402:
foreach (v, neighs; adjacencyMap) {
minDistance[v] = Weight.max;
foreach (immutable n; neighs)
minDistance[n.target] = Weight.max;
}
minDistance[source] = 0;
alias Pair = Tuple!(Weight, Vertex)
auto vertexQueue = redBlackTree(Pair(minDistance[source], source));
typeof(typeof(return)[1]) previous;
while (!vertexQueue.empty) {
const u = vertexQueue.front
vertexQueue.removeFront
if (u == target)
break;
// Visit each edge exiting u.
vertexQueue.removeKey(Pair(minDistance[v],
vertexQueue.insert(Pair(minDistance[v], v));
}▼
}
▲ }
}
Line 452:
void main() {
AdjacencyMap adj;▼
immutable arcs = [tuple("a", "b", 7),
tuple("a", "c", 9),
Line 462 ⟶ 461:
tuple("d", "e", 6),
tuple("e", "f", 9)];
▲ AdjacencyMap adj;
foreach (arc; arcs) {
// Edges in both directions for an undirected graph▼
adj[arc[0]] ~= Neighbor(arc[1], arc[2]);
//adj[arc[1]] ~= Neighbor(arc[0], arc[2]); //
}
Line 472 ⟶ 473:
const previous = minDist_prev[1];
writeln(
writeln("Path
}</lang>
{{out}}
<pre>Distance from "a" to "e":
Path
=={{header|Go}}==
|