private readonly decimal[] _distTo; // distTo[v] = distance of shortest s->v path #endregion Fields #region Constructors /** * Computes a shortest paths tree from <tt>s</tt> to every other vertex in * the edge-weighted digraph <tt>G</tt>. * @param G the edge-weighted digraph * @param s the source vertex * @throws IllegalArgumentException if an edge weight is negative * @throws IllegalArgumentException unless 0 ≤ <tt>s</tt> ≤ <tt>V</tt> - 1 */ public ShortestNeuronPath(NeuronGraph G, int s) { _distTo = new decimal[G.V()]; edgeTo = new DirectedEdge[G.V()]; for (int v = 0; v < G.V(); v++) _distTo[v] = decimal.MaxValue; _distTo[s] = 0.0M; // relax vertices in order of distance from s pq = new IndexMinPQ<decimal>(G.V()); pq.Insert(s, _distTo[s]); while (!pq.IsEmpty()) { int v = pq.DelMin(); foreach (DirectedEdge e in G.adj(v)) relax(e); } }
private Queue<Int32> queue; // queue of vertices to relax #endregion Fields #region Constructors public BellmanFordSP(NeuronGraph G, int s) { distTo = new decimal[G.V()]; edgeTo = new DirectedEdge[G.V()]; onQueue = new Boolean[G.V()]; for (int v = 0; v < G.V(); v++) distTo[v] = decimal.MaxValue; distTo[s] = 0.0M; // Bellman-Ford algorithm queue = new Queue<Int32>(); queue.Enqueue(s); onQueue[s] = true; while (queue.Count != 0) { int v = queue.Dequeue(); // Console.WriteLine("Relaxing edge {0}", v); onQueue[v] = false; relax(G, v); } }
// relax vertex v and put other endpoints on queue if changed private void relax(NeuronGraph G, int v) { foreach(DirectedEdge e in G.adj(v)) { int w = e.to(); decimal wdist = distTo[w]; decimal vdist = distTo[v]; if (distTo[w] > distTo[v] + e.weight()) { // Console.WriteLine("LOL"); distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; if (w == 2000) { Console.WriteLine(distTo[w]); } if (!onQueue[w]) { queue.Enqueue(w); onQueue[w] = true; } } if (cost++%G.V() == 0) { // Console.Write("Cost is {0} and we're hitting this, finding negative cycle", cost); findNegativeCycle(); } } }