//------------------------- Dijkstra Algorithm ----------------------------- //code below lifted mostly from CLR import java.util.*; import java.lang.*; import Graph.*; public final class Dijkstra { private HashMap d; /** d[v] constains shortest distance from source to node v*/ private HashMap p; /** p[v] constains immediate predecessor of v in shortest parth from source. */ Node src; Graph g; Node[] nodes; ArrayList pQ; ArrayList S; //------------ access functions ------ public HashMap getPred() { return p; }; public HashMap getD() { return d; }; public HashMap runDijkstra(Graph g, Node src) { this.g = g; this.src = src; this.nodes = g.getNodesArray(); InitializeSingleSource(g, src); S = new ArrayList(nodes.length); while (!pQ.isEmpty()) { Node u = (Node) pQ.remove(0); S.add(u); Node[] neighbors = g.getNeighborsOf(u); for (int j=0; j du + w) { d.put(v, new Double(du+w)); p.put(v, u); UpdatePQ(v, du+w); //ensure that PQ remains sorted } } //-------------------------- Breadth First Search ------------------------ /** Bfs solves SSSP in O(V+E) time and so is faster than Dijkstra when it comes to unweighted (or when weight is measured by hop-counts) graphs. Algorithm more or less follows CLR, page 470. */ public HashMap runBFS(Graph g, Node src) { this.g = g; this.nodes = g.getNodesArray(); this.src = src; //some initializations: HashMap color = new HashMap(); /* 1 = White, 2 = Gray, 3=Black*/ ArrayList Q = new ArrayList(); for (int i=0; i S.size()) { //Check S first since its smaller vIndex = S.indexOf(v); if (vIndex!=-1) //S contains it, so pQ doesn't. No update reqd. return; } vIndex = pQ.indexOf(v); if (vIndex == -1) return; pQ.remove(vIndex); int newIndex = binarySearch(newWeight, 0, pQ.size()); pQ.add(newIndex, v); } private int binarySearch(double newWeight, int beginIndex, int endIndex) { while (beginIndex!=endIndex && endIndex>=beginIndex) { int mid = (int) (beginIndex+endIndex)/2; double midWeight = ( (Double)d.get((Node)pQ.get(mid))).doubleValue(); if (midWeight < newWeight) beginIndex = mid+1; else if (midWeight > newWeight) endIndex = mid-1; else return mid; //found! } //boundary conditions : if (endIndex <0) return 0; if (endIndex > pQ.size()) return pQ.size(); if (endIndex!=pQ.size()) { double endWeight = ((Double)d.get((Node)pQ.get(endIndex))).doubleValue(); if ( newWeight>endWeight) return endIndex+1; } return endIndex; } }