Dijkstra's algorithm: Difference between revisions

Line 973:
discovered.
 
<lang unicon>global qMice, goodMice, region, qMiceEmpty
global qMice, goodMice, region, qMiceEmpty
 
record Graph(nodes,weights)
record Node(name,targets,seenweight)
record Path(weight, nodes)
 
Line 983:
 
graph := getGraph()
repeat {
writes("What is the start node? ")
start := \graph.nodes[read()] | stop()
writes("What is the finish node? ")
finish := read() | stop()
 
insert(qMice, QMouse(graph,start,finish))
waitForCompletion() # block until all quantum mice have finished
 
showPath(getBestMouse(),start.name,finish)
cleanGraph(graph)
goodMice := set()
}
end
 
Line 1,009 ⟶ 1,014:
}
return graph
end
 
procedure cleanGraph(graph)
every (!graph.nodes).weight := &null
end
 
Line 1,014 ⟶ 1,023:
if \mouse then {
path := mouse.getPath()
writewrites("Best path fromWeight: ",startpath.weight," to-> ",finish," has weight: ",path.weight)
writes("Nodes:")
every writes(" ",!path.nodes)
write()
Line 1,023 ⟶ 1,031:
 
# A "Quantum-mouse" for traversing graphs.
# Each mouse follows no more than a single edge
class QMouse(graph, loc, finish, path, mouse)
 
method addPath(n); put(path, n); end
method getPath(); return path; end
method atEnd(); return (finish == loc.name); end
method visit(n) # Don't visit a nodeVisit if we don'vet gotalready have a cheaper pathroute to it alreadyn
newWeight := path.weight + graph.weights[loc.name||":"||n.name]
critical region[n]: if /n.weight | (newWeight < n.weight) then {
Line 1,043 ⟶ 1,051:
region := table()
every region[n := !g.nodes] := mutex()
qMice := set() # Set of all living 'quantum' mice
insert(qMice, self)
}
insert(qMice, self)
graph := g
loc := l
finish := f
/pathp := Path(0,[])
if \p then path := Path(p.weight,copy(p.nodes))
if *path.nodes > 0 then path.weight +:= g.weights[path.nodes[-1]||":"||loc.name]
path.weight +:= g.weights[path.nodes[-1]||":"||loc.name]
put(path.nodes, loc.name)
mouse := thread {
if atEnd() then insert(goodMice, self) # This mouse found a finish
else every insert(qMice, QMouse(g,visit(!loc.targets),f,path)) # MakeTry more mice
delete(qMice, self) # Kill this mouse
if *qMice=0 then signal(qMiceEmpty) # All mice are dead
}
end
Line 1,072 ⟶ 1,081:
procedure waitForCompletion()
critical qMiceEmpty: while *qMice > 0 do wait(qMiceEmpty)
end</lang>
</lang>
 
Sample run:
Line 1,091 ⟶ 1,101:
What is the start node? a
What is the finish node? f
Weight: 11 -> a c f
Best path from a to f has weight: 11
What is the start node? a
Nodes: a c f
What is the finish node? e
Weight: 26 -> a c d e
What is the start node? f
What is the finish node? a
BestNo path from af to f has weight: 11a
What is the start node?
->
</pre>