private void Relax(WeightedDiGraph <T> G, T v) { foreach (var e in G.Adj(v)) { T w = e.To(); if (distTo[w] > distTo[v] + e.Weight) { distTo[w] = distTo[v] + e.Weight; edgeTo[w] = e; if (!onQueue[w]) { queue.Enqueue(w); onQueue[w] = true; } } if (cost++ % G.V() == 0) { FindNegativeCycle(); if (HasNegativeCycle()) { return; // found a negative cycle } } } }
public Dijkstra(WeightedDiGraph G, int s) { this.s = s; int V = G.V(); marked = new bool[V]; edgeTo = new Edge[V]; cost = new double[V]; for (var i = 0; i < V; ++i) { cost[i] = Double.MaxValue; } cost[s] = 0; pq = new IndexMinPQ <Double>(V); pq.Insert(s, 0); while (!pq.IsEmpty) { var v = pq.DelMin(); marked[v] = true; foreach (var e in G.adj(v)) { Relax(G, e); } } }
public TopologicalSortShortestPath(WeightedDiGraph G, int s) { this.s = s; int V = G.V(); marked = new bool[V]; edgeTo = new Edge[V]; cost = new double[V]; for (var i = 0; i < V; ++i) { cost[i] = Double.MaxValue; } cost[s] = 0; DepthFirstPostOrder dfo = new DepthFirstPostOrder(G.ToDiGraph()); foreach (var v in dfo.PostOrder()) { foreach (var e in G.adj(v)) { Relax(G, e); } } }
public void Test() { WeightedDiGraph G = GraphGenerator.directedEdgeWeightedGraph(); Dijkstra dijkstra = new Dijkstra(G, 0); for (var v = 1; v < G.V(); ++v) { if (!dijkstra.HasPathTo(v)) { Console.WriteLine("Path not found for {0}", v); continue; } IEnumerable <Edge> path = dijkstra.PathTo(v); console.WriteLine(ToString(path)); Console.WriteLine(ToString(path)); } }
public void Test() { WeightedDiGraph G = GraphGenerator.directedEdgeWeightedGraph(); BellmanFulkerson BellmanFulkerson = new BellmanFulkerson(G, 0); for (var v = 1; v < G.V(); ++v) { if (!BellmanFulkerson.HasPathTo(v)) { Console.WriteLine("Path not found for {0}", v); continue; } IEnumerable <Edge> path = BellmanFulkerson.PathTo(v); console.WriteLine(ToString(path)); Console.WriteLine(ToString(path)); } }
public BellmanFulkerson(WeightedDiGraph G, int s) { this.s = s; var V = G.V(); cost = new double[V]; for (var v = 0; v < V; ++v) { cost[v] = Double.MaxValue; } edgeTo = new Edge[V]; cost[s] = 0; for (var j = 0; j < V; ++j) { for (var v = 0; v < V; ++v) { foreach (var e in G.adj(v)) { Relax(G, e); } } } negativeCycles = false; for (var v = 0; v < V; ++v) { foreach (var e in G.adj(v)) { if (Relax(G, e)) { negativeCycles = true; } } } }