SLIDE 38 18/9/2007 I2A 98 slides 11
38
Richard Bornat Dept of Computer Science
The Dijkstra algorithm.
The pathfinding procedure is exactly the same mechanism as before, with the exception that now I queue distances as well:
class EdgeList { public Edge hd; public EdgeList tl; } private class PathInfo { public Node r; public EdgeList path; public int len; } public void enqueue(PriorityQueue q, Node r, EdgeList path, int len) { PathInfo pi = new PathInfo(); pi.r=r; pi.path=path; pi.len=len; q.insert(pi,len); } public EdgeList Dijkstrafind(Node s) { Queue q = new Queue; enqueue(q,this,null,0); while (!q.isempty()) { PathInfo pi=(PathInfo)q.remove(); Node r = pi.r; EdgeList path = pi.path; int len=pi.len; if (r==s) return path; else if (!r.visited) { r.visited=true; for (int i=0; i<r.edges.length; i++) { Edgelist path2 = new EdgeList(); path2.hd = r.edges[i]; path2.tl = path; enqueue(q,r.edges[i].to,path2,len+r.edges[i].weight); } } } return null; }