public void Relax(EdgeWeightedDigraph g, int v) { foreach (DirectedEdge e in g.Adj(v)) { int w = e.To; switch (_pathType) { case PathType.Lagrest: if (_distTo[w] < _distTo[v] + e.Weight) { _distTo[w] = _distTo[v] + e.Weight; _edgeTo[w] = e; } break; case PathType.Shortest: if (_distTo[w] > _distTo[v] + e.Weight) { _distTo[w] = _distTo[v] + e.Weight; _edgeTo[w] = e; } break; } } }
private void dfs(EdgeWeightedDigraph edgeWeightedDigraph, int num) { this.onStack[num] = true; this.marked[num] = true; Iterator iterator = edgeWeightedDigraph.adj(num).iterator(); while (iterator.hasNext()) { DirectedEdge directedEdge = (DirectedEdge)iterator.next(); int num2 = directedEdge.to(); if (this.cycle != null) { return; } if (!this.marked[num2]) { this.edgeTo[num2] = directedEdge; this.dfs(edgeWeightedDigraph, num2); } else if (this.onStack[num2]) { this.cycle = new Stack(); while (directedEdge.from() != num2) { this.cycle.push(directedEdge); directedEdge = this.edgeTo[directedEdge.from()]; } this.cycle.push(directedEdge); } } this.onStack[num] = false; }
private static void ShortestPath() { string filename = "mediumEWD.txt"; Scanner scanner = new Scanner(new StreamReader(File.OpenRead(filename))); IEdgeWeightedDIgraph G = new EdgeWeightedDigraph(scanner); StdOut.Print("输入一个边:"); int s = StdIn.ReadInt(); IShortestPath sp = new DijkstraSP(G, s); for (int t = 0; t < G.V; t++) { StdOut.Print(s + " to " + t); StdOut.Printf(" ({0}): ", sp.DistTo(t)); if (sp.HasPathTo(t)) { foreach (var e in sp.PathTo(t)) { StdOut.Print(e + " "); } } StdOut.Println(); } DijkstraAllPairsSP allPairsSP = new DijkstraAllPairsSP(G); StdOut.Println(); StdOut.Println(allPairsSP.Dist(1, 28)); //string filename2 = "tinyEWDAG.txt"; //scanner = new Scanner(new StreamReader(File.OpenRead(filename2))); //G = new EdgeWeightedDigraph(scanner); //IShortestPath sp2 = new AcyclicSP(G, s); //for (int t = 0; t < G.V; t++) //{ // StdOut.Print(s + " to " + t); // StdOut.Printf(" ({0}): ", sp2.DistTo(t)); // if (sp2.HasPathTo(t)) // foreach (var e in sp.PathTo(t)) // { // StdOut.Print(e + " "); // } // StdOut.Println(); //} //filename = "tinyEWDnc.txt"; //scanner = new Scanner(new StreamReader(File.OpenRead(filename))); //G = new EdgeWeightedDigraph(scanner); //sp = new BellmanFordSP(G, s); //for (int t = 0; t < G.V; t++) //{ // StdOut.Print(s + " to " + t); // StdOut.Printf(" ({0}): ", sp.DistTo(t)); // if (sp.HasPathTo(t)) // foreach (var e in sp.PathTo(t)) // { // StdOut.Print(e + " "); // } // StdOut.Println(); //} }
public ShortestPath(EdgeWeightedDigraph graph, int source) { shortestPathTree = new WeightedDirectedEdge[graph.VertexNumber]; shortestPathTree[source] = Source; var edges = new BinaryHeap <WeightedDirectedEdge>(graph.EdgeNumber); foreach (var edge in graph.GetAllEdges()) { if (edge.Weight < 0) { throw new ArgumentOutOfRangeException(nameof(graph), "Dijkstra's algorithm only supports non-negative weights."); } edges.Insert(edge); } var edgeNumber = 0; while (edgeNumber <= shortestPathTree.Length - 1 && edges.Size > 0) { var shortestEdge = edges.Pop(); if (shortestPathTree[shortestEdge.To] == null) { shortestPathTree[shortestEdge.To] = shortestEdge; edgeNumber++; } } }
private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on longest s->v path public AcyclicLP(EdgeWeightedDigraph G, int s) { distTo = new double[G.V()]; edgeTo = new DirectedEdge[G.V()]; validateVertex(s); for (int v = 0; v < G.V(); v++) { distTo[v] = double.NegativeInfinity; } distTo[s] = 0.0; // relax vertices in toplogical order Topological topological = new Topological(G); if (!topological.hasOrder()) { throw new System.Exception("Digraph is not acyclic."); } foreach (int v in topological.Order()) { foreach (DirectedEdge e in G.Adj(v)) { relax(e); } } }
/// <summary> /// check that algorithm computes either the topological order or finds a directed cycle /// </summary> /// <param name="g"></param> /// <param name="v"></param> private void dfs(EdgeWeightedDigraph g, int v) { this._onStack[v] = true; this._marked[v] = true; foreach (DirectedEdge e in g.Adj[v]) { int w = e.To(); if (this.Cycle != null) { // short circuit if directed cycle found return; } else if (!this._marked[w]) { //found new vertex, so recur this._edgeTo[w] = e; this.dfs(g, w); } else if (this._onStack[w]) { // trace back directed cycle this.Cycle = new Stack<DirectedEdge>(); while (e.From() != w) { this.Cycle.Push(e); //e = this._edgeTo[e.From()]; } this.Cycle.Push(e); return; } } this._onStack[v] = false; }
/// <summary> /// Constructs a new PathFinder instance for the specified Map /// </summary> /// <param name="map">The Map that this PathFinder instance will run shortest path algorithms on</param> /// <exception cref="ArgumentNullException">Thrown on null map</exception> public PathFinder( IMap map ) { if ( map == null ) { throw new ArgumentNullException( "map", "Map cannot be null" ); } _map = map; _graph = new EdgeWeightedDigraph( _map.Width * _map.Height ); foreach ( Cell cell in _map.GetAllCells() ) { if ( cell.IsWalkable ) { int v = IndexFor( cell ); foreach ( Cell neighbor in _map.GetBorderCellsInRadius( cell.X, cell.Y, 1 ) ) { if ( neighbor.IsWalkable ) { int w = IndexFor( neighbor ); _graph.AddEdge( new DirectedEdge( v, w, 1.0 ) ); _graph.AddEdge( new DirectedEdge( w, v, 1.0 ) ); } } } } }
// se crea el grafo a partir de la matriz logica private void CreateGraph() { graph = new EdgeWeightedDigraph((int)(rows * columns)); // adyacencias de cada casilla (derecha, abajo, izquierda, arriba) Vector2[] directions = { new Vector2(0, 1), new Vector2(1, 0), new Vector2(0, -1), new Vector2(-1, 0) }; // si la casilla no es de tipo Roca, le establecemos union // con todas sus adyacentes que tampoco sean de tipo Roca for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (puzzle.GetType(i, j) != (int)TipoCasilla.Rocas) { foreach (Vector2 v in directions) { int ni = i + (int)v.y; int nj = j + (int)v.x; if (ni >= 0 && ni < rows && nj >= 0 && nj < columns) { if (puzzle.GetType(ni, nj) != (int)TipoCasilla.Rocas) { DirectedEdge a = new DirectedEdge((int)(j + columns * i), (int)(nj + columns * ni), values[puzzle.GetType(ni, nj)]); graph.AddEdge(a); } } } } } } }
public BellmanFordSP(EdgeWeightedDigraph g, int s) { _disTo = new double[g.Vertice]; _onQ = new bool[g.Vertice]; _q = new Queue <int>(); _paths = new DirectedEdge[g.Vertice]; //_cycle = new List<DirectedEdge>(); for (int i = 0; i < _disTo.Length; i++) { if (s == i) { _disTo[s] = 0; } else { _disTo[i] = ShortestPath.INFINITE; } } _q.Enqueue(s); _onQ[s] = true; while (_q.Count != 0) { int v = _q.Dequeue(); _onQ[v] = true; Relax(g, v); } }
/// <summary> /// Constructs a new PathFinder instance for the specified Map that will consider diagonal movement by using the specified diagonalCost /// </summary> /// <param name="map">The Map that this PathFinder instance will run shortest path algorithms on</param> /// <param name="diagonalCost"> /// The cost of diagonal movement compared to horizontal or vertical movement. /// Use 1.0 if you want the same cost for all movements. /// On a standard cartesian map, it should be sqrt(2) (1.41) /// </param> /// <exception cref="ArgumentNullException">Thrown when a null map parameter is passed in</exception> public PathFinder(IMap map, double diagonalCost) { _map = map ?? throw new ArgumentNullException(nameof(map), "Map cannot be null"); _graph = new EdgeWeightedDigraph(_map.Width * _map.Height); foreach (ICell cell in _map.GetAllCells()) { if (cell.IsWalkable) { int v = IndexFor(cell); foreach (ICell neighbor in _map.GetBorderCellsInSquare(cell.X, cell.Y, 1)) { if (neighbor.IsWalkable) { int w = IndexFor(neighbor); if (neighbor.X != cell.X && neighbor.Y != cell.Y) { _graph.AddEdge(new DirectedEdge(v, w, diagonalCost)); _graph.AddEdge(new DirectedEdge(w, v, diagonalCost)); } else { _graph.AddEdge(new DirectedEdge(v, w, 1.0)); _graph.AddEdge(new DirectedEdge(w, v, 1.0)); } } } } } }
/// <summary> /// Computes a shortest paths tree from the specified sourceVertex to every other vertex in the edge-weighted directed graph /// </summary> /// <param name="graph">The edge-weighted directed graph</param> /// <param name="sourceVertex">The source vertex to compute the shortest paths tree from</param> /// <exception cref="ArgumentOutOfRangeException">Throws an ArgumentOutOfRangeException if an edge weight is negative</exception> /// <exception cref="ArgumentNullException">Thrown if EdgeWeightedDigraph is null</exception> public DijkstraShortestPath(EdgeWeightedDigraph graph, int sourceVertex) { if (graph == null) { throw new ArgumentNullException("graph", "EdgeWeightedDigraph cannot be null"); } foreach (DirectedEdge edge in graph.Edges()) { if (edge.Weight < 0) { throw new ArgumentOutOfRangeException($"Edge: '{edge}' has negative weight"); } } _distanceTo = new double[graph.NumberOfVertices]; _edgeTo = new DirectedEdge[graph.NumberOfVertices]; for (int v = 0; v < graph.NumberOfVertices; v++) { _distanceTo[v] = double.PositiveInfinity; } _distanceTo[sourceVertex] = 0.0; _priorityQueue = new IndexMinPriorityQueue <double>(graph.NumberOfVertices); _priorityQueue.Insert(sourceVertex, _distanceTo[sourceVertex]); while (!_priorityQueue.IsEmpty()) { int v = _priorityQueue.DeleteMin(); foreach (DirectedEdge edge in graph.Adjacent(v)) { Relax(edge); } } }
void Start() { double a = double.PositiveInfinity; double b = (double.PositiveInfinity + 10.0); print(a > b); print(a < b); print(a == b); EdgeWeightedDigraph G = new EdgeWeightedDigraph(Graph); int s = 0; // compute shortest paths DijkstraSP sp = new DijkstraSP(G, s); // print shortest path for (int t = 0; t < G.V(); t++) { if (sp.hasPathTo(t)) { string str = s + " to " + t + " Distance=" + sp.DistTo(t); foreach (DirectedEdge e in sp.PathTo(t)) { str += (e + "\t"); } print(str); } else { print(s + " to " + t + " no path\n"); } } }
/// <summary> /// Computes a shortest paths tree from the specified sourceVertex to every other vertex in the edge-weighted directed graph /// </summary> /// <param name="graph">The edge-weighted directed graph</param> /// <param name="sourceVertex">The source vertex to compute the shortest paths tree from</param> /// <exception cref="ArgumentOutOfRangeException">Throws an ArgumentOutOfRangeException if an edge weight is negative</exception> /// <exception cref="ArgumentNullException">Thrown if EdgeWeightedDigraph is null</exception> public DijkstraShortestPath( EdgeWeightedDigraph graph, int sourceVertex ) { if ( graph == null ) { throw new ArgumentNullException( "graph", "EdgeWeightedDigraph cannot be null" ); } foreach ( DirectedEdge edge in graph.Edges() ) { if ( edge.Weight < 0 ) { throw new ArgumentOutOfRangeException( string.Format( "Edge: '{0}' has negative weight", edge ) ); } } _distanceTo = new double[graph.NumberOfVertices]; _edgeTo = new DirectedEdge[graph.NumberOfVertices]; for ( int v = 0; v < graph.NumberOfVertices; v++ ) { _distanceTo[v] = Double.PositiveInfinity; } _distanceTo[sourceVertex] = 0.0; _priorityQueue = new IndexMinPriorityQueue<double>( graph.NumberOfVertices ); _priorityQueue.Insert( sourceVertex, _distanceTo[sourceVertex] ); while ( !_priorityQueue.IsEmpty() ) { int v = _priorityQueue.DeleteMin(); foreach ( DirectedEdge edge in graph.Adjacent( v ) ) { Relax( edge ); } } }
private void Dfs(EdgeWeightedDigraph g, int v) { marked[v] = true; onStack[v] = true; foreach (var e in g.Adj(v)) { int w = e.To; if (HasCycle()) { return; } else if (!marked[w]) { edgeTo[w] = e; Dfs(g, w); } else if (onStack[w]) { cycle = new Stack <int>(); for (int x = v; x != w; x = edgeTo[x].To) { cycle.Push(x); } cycle.Push(w); cycle.Push(v); } } onStack[v] = false; }
public ShortestPath(EdgeWeightedDigraph g, int s) { _s = s; _disTo = new double[g.Vertice]; for (int i = 0; i < _disTo.Length; i++) { if (s == i) { _disTo[s] = 0; } else { _disTo[i] = INFINITE; } } _paths = new DirectedEdge[g.Vertice]; _pq = new Dictionary <int, double>(); _pq.Add(s, 0.0); while (_pq.Count != 0) { Relax(g, GetTheKeyWithLowestWeight()); } }
public void Search(EdgeWeightedDigraph g, DirectedEdge s) { _onList[s.To] = true; _marked[s.To] = true; foreach (var temp in g.Adj(s.To)) { if (HasCycle()) { return; } else if (!_marked[temp.From]) { _edgeTo[temp.From] = s; Search(g, temp); } else if (_onList[temp.From]) { _cycle = new List <DirectedEdge>(); for (int i = s.From; i != temp.From; i = _edgeTo[i].From) { _cycle.Add(_edgeTo[i]); } _cycle.Add(temp); _cycle.Add(s); } } _onList[s.From] = false; }
/// <summary> /// Constructs a new PathFinder instance for the specified Map /// </summary> /// <param name="map">The Map that this PathFinder instance will run shortest path algorithms on</param> /// <exception cref="ArgumentNullException">Thrown on null map</exception> public PathFinder(IMap map) { if (map == null) { throw new ArgumentNullException("map", "Map cannot be null"); } _map = map; _graph = new EdgeWeightedDigraph(_map.Width * _map.Height); foreach (Cell cell in _map.GetAllCells()) { if (cell.IsWalkable) { int v = IndexFor(cell); foreach (Cell neighbor in _map.GetBorderCellsInRadius(cell.X, cell.Y, 1)) { if (neighbor.IsWalkable) { int w = IndexFor(neighbor); _graph.AddEdge(new DirectedEdge(v, w, 1.0)); _graph.AddEdge(new DirectedEdge(w, v, 1.0)); } } } } }
private EdgeWeightedDigraph CreateDigraph() { EdgeWeightedDigraph graph = new EdgeWeightedDigraph(9); // 2 -[0.3]-> 3 // ^ ^ // / / // [0.2] [0.3] // / / // 0 -[0.5]-> 1 -[1.2]-> 4 // \ ^ // \ \ // [0.3] [0.1] // \ \ // 5 -[0.5]-> 6 // // 7 -[0.1]-> 8 graph.AddEdge(new Edge(0, 1, .5)); graph.AddEdge(new Edge(0, 2, .2)); graph.AddEdge(new Edge(1, 3, .3)); graph.AddEdge(new Edge(1, 4, 1.2)); graph.AddEdge(new Edge(1, 5, .3)); graph.AddEdge(new Edge(2, 3, .3)); graph.AddEdge(new Edge(5, 6, .5)); graph.AddEdge(new Edge(6, 4, .1)); graph.AddEdge(new Edge(7, 8, .1)); return(graph); }
static void Main(string[] args) { EdgeWeightedDigraph g = new EdgeWeightedDigraph(8); foreach (var temp in TestEdgeData) { g.AddEdge(temp); } SP sp; //sp = new ShortestPath(g, 0); sp = new BellmanFordSP(g, 0); for (int i = 0; i < g.Vertice; i++) { Console.Write(0 + "to" + i + "( {0} )", sp.DisTo(i)); if (sp.HasPath(i)) { foreach (DirectedEdge temp in sp.PathTo(i)) { Console.Write(" " + temp.ToString() + " "); } Console.WriteLine(); } } }
private void dfs(EdgeWeightedDigraph edgeWeightedDigraph, int num) { this.marked[num] = true; int[] arg_23_0 = this.pre; int num2 = this.preCounter; int arg_23_2 = num2; this.preCounter = num2 + 1; arg_23_0[num] = arg_23_2; this.preorder.enqueue(Integer.valueOf(num)); Iterator iterator = edgeWeightedDigraph.adj(num).iterator(); while (iterator.hasNext()) { DirectedEdge directedEdge = (DirectedEdge)iterator.next(); int num3 = directedEdge.to(); if (!this.marked[num3]) { this.dfs(edgeWeightedDigraph, num3); } } this.postorder.enqueue(Integer.valueOf(num)); int[] arg_9F_0 = this.post; num2 = this.postCounter; int arg_9F_2 = num2; this.postCounter = num2 + 1; arg_9F_0[num] = arg_9F_2; }
public void Run() { // create random DAG with V vertices and E edges; then add F random edges const int vv = 50; const int e = 100; const int f = 20; var digraph = new EdgeWeightedDigraph(vv); var vertices = new int[vv]; for (var i = 0; i < vv; i++) { vertices[i] = i; } StdRandom.Shuffle(vertices); for (var i = 0; i < e; i++) { int v, w; do { v = StdRandom.Uniform(vv); w = StdRandom.Uniform(vv); } while (v >= w); var weight = StdRandom.Uniform(); digraph.AddEdge(new DirectedEdge(v, w, weight)); } // add F extra edges for (var i = 0; i < f; i++) { var v = StdRandom.Uniform(vv); var w = StdRandom.Uniform(vv); var weight = StdRandom.Uniform(0.0, 1.0); digraph.AddEdge(new DirectedEdge(v, w, weight)); } Console.WriteLine(digraph); // find a directed cycle var finder = new EdgeWeightedDirectedCycle(digraph); if (finder.HasCycle()) { Console.Write("Cycle: "); foreach (var edge in finder.Cycle()) { Console.Write(edge + " "); } Console.WriteLine(); } // or give topologial sort else { Console.WriteLine("No directed cycle"); } Console.ReadLine(); }
public DijkstraAllPairsShortestPath(EdgeWeightedDigraph g) { all = new DijkstraShortestPath[g.Vcount]; for (int i = 0; i < g.Vcount; i++) { all[i] = new DijkstraShortestPath(g, i); } }
public DijkstraAllPairsSP(EdgeWeightedDigraph ewd) { this.all = new DijkstraSP[ewd.V()]; for (int i = 0; i < ewd.V(); i++) { this.all[i] = new DijkstraSP(ewd, i); } }
public void AddEdge_WhenGraphHad0Edges_WillNowHave1Edge() { EdgeWeightedDigraph graph = new EdgeWeightedDigraph(5); graph.AddEdge(new DirectedEdge(1, 2, 1.0)); Assert.AreEqual(1, graph.NumberOfEdges); }
public DijkstraAllPairsSP(EdgeWeightedDigraph G) { all = new DijkstraSP[G.V()]; for (int v = 0; v < G.V(); v++) { all[v] = new DijkstraSP(G, v); } }
public void Constructor_WhenGraphHasEdgesWithNegativeWeights_WillThrowArgumentOutOfRangeException() { EdgeWeightedDigraph digraph = new EdgeWeightedDigraph(2); digraph.AddEdge(new DirectedEdge(0, 1, -1.5)); Assert.ThrowsException <ArgumentOutOfRangeException>(() => new DijkstraShortestPath(digraph, 0)); }
public DijkstraAllPairSP(EdgeWeightedDigraph g) { all = new ShortestPath[g.Vertice]; for (int i = 0; i < g.Vertice; i++) { all[i] = new ShortestPath(g, i); } }
public Topological(EdgeWeightedDigraph g) { //EdgeWeightedDirectedCycle cycleFinder = new EdgeWeightedDirectedCycle(g); //if (!cycleFinder.HasCycle()) //{ DepthFirstOrder dfs = new DepthFirstOrder(g); this.Order = dfs.ReversePost; //} }
public static TopologicalChecker Create(EdgeWeightedDigraph graph) { if (graph == null) { throw new ArgumentNullException(nameof(graph)); } return(new TopologicalChecker(graph)); }
public Topological(EdgeWeightedDigraph graph) { var finder = new EdgeWeightedDirectedCycle(graph); if (!finder.HasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(graph); order = dfs.ReversePost(); } }
public Topological(EdgeWeightedDigraph ewd) { EdgeWeightedDirectedCycle edgeWeightedDirectedCycle = new EdgeWeightedDirectedCycle(ewd); if (!edgeWeightedDirectedCycle.hasCycle()) { DepthFirstOrder depthFirstOrder = new DepthFirstOrder(ewd); this.order = depthFirstOrder.reversePost(); } }
public void OutDegree_WhenVertexHas3EdgesToOtherVertices_WillBe3() { EdgeWeightedDigraph graph = new EdgeWeightedDigraph(5); graph.AddEdge(new DirectedEdge(1, 2, 1.0)); graph.AddEdge(new DirectedEdge(1, 3, 1.5)); graph.AddEdge(new DirectedEdge(1, 4, 1.0)); Assert.AreEqual(3, graph.OutDegree(1)); }
public EdgeWeightedTopological(EdgeWeightedDigraph g) { var cycleFinder = new EdgeWeightedDirectedCycle(g); if (!cycleFinder.HasCycle()) { var dfs = new EdgeWeightedDigraphDepthFirstOrder(g); order = dfs.ReversePost(); } }
/// <summary> /// Determines whether the edge-weighted digraph G has a directed this.Cycle and, if so, finds such a this.Cycle /// </summary> /// <param name="g"></param> public EdgeWeightedDirectedCycle(EdgeWeightedDigraph g) { this._marked = new bool[g.V()]; this._onStack = new bool[g.V()]; this._edgeTo = new DirectedEdge[g.V()]; for (int v = 0; v < g.V(); v++) if (!this._marked[v]) this.dfs(g, v); }
public Topological(EdgeWeightedDigraph G) { EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(G); order = dfs.reversePost(); } }
private void findNegativeCycle() { int V = this._edgeTo.Length; EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V); for (int v = 0; v < V; v++) if (this._edgeTo[v] != null) spt.AddEdge(this._edgeTo[v]); EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(spt); this._cycle = finder.Cycle; }
public DepthFirstOrder(EdgeWeightedDigraph g) { this.Pre = new Queue<int>(); this.Post = new Queue<int>(); this.ReversePost = new Stack<int>(); this._marked = new bool[g.V()]; for (int v = 0; v < g.V(); v++) if (!this._marked[v]) this.dfs(g, v); }
private void dfs(EdgeWeightedDigraph g, int v) { this.Pre.Enqueue(v); this._marked[v] = true; foreach (DirectedEdge e in g.Adj[v]) if (!this._marked[e.To()]) this.dfs(g, e.To()); this.Post.Enqueue(v); this.ReversePost.Push(v); }
// TODO: This method should be private and should be called from the bottom of the constructor /// <summary> /// check optimality conditions: /// </summary> /// <param name="graph">The edge-weighted directed graph</param> /// <param name="sourceVertex">The source vertex to check optimality conditions from</param> /// <returns>True if all optimality conditions are met, false otherwise</returns> /// <exception cref="ArgumentNullException">Thrown on null EdgeWeightedDigraph</exception> public bool Check( EdgeWeightedDigraph graph, int sourceVertex ) { if ( graph == null ) { throw new ArgumentNullException( "graph", "EdgeWeightedDigraph cannot be null" ); } if ( _distanceTo[sourceVertex] != 0.0 || _edgeTo[sourceVertex] != null ) { return false; } for ( int v = 0; v < graph.NumberOfVertices; v++ ) { if ( v == sourceVertex ) { continue; } if ( _edgeTo[v] == null && _distanceTo[v] != double.PositiveInfinity ) { return false; } } for ( int v = 0; v < graph.NumberOfVertices; v++ ) { foreach ( DirectedEdge edge in graph.Adjacent( v ) ) { int w = edge.To; if ( _distanceTo[v] + edge.Weight < _distanceTo[w] ) { return false; } } } for ( int w = 0; w < graph.NumberOfVertices; w++ ) { if ( _edgeTo[w] == null ) { continue; } DirectedEdge edge = _edgeTo[w]; int v = edge.From; if ( w != edge.To ) { return false; } if ( _distanceTo[v] + edge.Weight != _distanceTo[w] ) { return false; } } return true; }
public AcyclicSP(EdgeWeightedDigraph g, int s) { this._g = g; this._s = s; this.DistTo = new double[g.V()]; this._edgeTo = new DirectedEdge[g.V()]; for (int v = 0; v < g.V(); v++) this.DistTo[v] = double.PositiveInfinity; this.DistTo[s] = 0d; Topological top = new Topological(g); foreach (int v in top.Order) foreach (DirectedEdge e in g.Adj[v]) this.relax(e); }
public AcyclicLP(EdgeWeightedDigraph g, int s) { this._g = g; this._s = s; this.DistTo = new double[g.V()]; this._edgeTo = new DirectedEdge[g.V()]; for (int v = 0; v < g.V(); v++) this.DistTo[v] = double.NegativeInfinity; this.DistTo[s] = 0d; Topological top = new Topological(g); if (top.Order == null) throw new Exception("Digraph is not acyclic."); foreach (int v in top.Order) foreach (DirectedEdge e in g.Adj[v]) this.relax(e); }
public DijkstraSP(EdgeWeightedDigraph g, int s) { this._g = g; this._s = s; this.DistTo = new double[g.V()]; this._edgeTo = new DirectedEdge[g.V()]; this._pq = new IndexMinPQ<double>(g.V()); for (int v = 0; v < g.V(); v++) this.DistTo[v] = double.PositiveInfinity; this.DistTo[s] = 0d; this._pq.Insert(s, 0d); while (!this._pq.IsEmpty()) { int v = this._pq.DelMin(); foreach (DirectedEdge e in g.Adj[v]) this.relax(e); } }
private void relax(EdgeWeightedDigraph g, int v) { foreach (DirectedEdge e in g.Adj[v]) { int w = e.To(); if (this._distTo[w] > this._distTo[v] + e.Weight()) { this._distTo[w] = this._distTo[v] + e.Weight(); this._edgeTo[w] = e; if (!this._onQueue[w]) { this._queue.Enqueue(w); this._onQueue[w] = true; } } if (this._cost++ % g.V() == 0) { this.findNegativeCycle(); if (this.hasNegativeCycle()) return; } } }
public BellmanFordSP(EdgeWeightedDigraph g, int s) { this._g = g; this._s = s; this._distTo = new double[g.V()]; this._edgeTo = new DirectedEdge[g.V()]; this._onQueue = new bool[g.V()]; this._queue = new Queue<int>(); for (int v = 0; v < g.V(); v++) this._distTo[v] = double.PositiveInfinity; this._distTo[s] = 0d; this._queue.Enqueue(s); this._onQueue[s] = true; while (this._queue.Count != 0 && !this.hasNegativeCycle()) { int v = this._queue.Dequeue(); this._onQueue[v] = false; this.relax(g, v); } }
public void TestDijkstraSP() { EdgeWeightedDigraph g = new EdgeWeightedDigraph(8); g.AddEdge(new DirectedEdge(5, 4, 0.35d)); g.AddEdge(new DirectedEdge(4, 7, 0.37d)); g.AddEdge(new DirectedEdge(5, 7, 0.28d)); g.AddEdge(new DirectedEdge(5, 1, 0.32d)); g.AddEdge(new DirectedEdge(4, 0, 0.38d)); g.AddEdge(new DirectedEdge(0, 2, 0.26d)); g.AddEdge(new DirectedEdge(3, 7, 0.39d)); g.AddEdge(new DirectedEdge(1, 3, 0.29d)); g.AddEdge(new DirectedEdge(7, 2, 0.34d)); g.AddEdge(new DirectedEdge(6, 2, 0.40d)); g.AddEdge(new DirectedEdge(3, 6, 0.52d)); g.AddEdge(new DirectedEdge(6, 0, 0.58d)); g.AddEdge(new DirectedEdge(6, 4, 0.93d)); Debug.WriteLine(g); //DijkstraSP mst = new DijkstraSP(g, 5); //Debug.WriteLine(mst); //AcyclicSP mst1 = new AcyclicSP(g, 5); //Debug.WriteLine(mst1); //AcyclicLP mst2 = new AcyclicLP(g, 5); //Debug.WriteLine(mst2); BellmanFordSP mst3 = new BellmanFordSP(g, 5); Debug.WriteLine(mst3); }
public DijkstraAllPairsSP(EdgeWeightedDigraph g) { this._all = new DijkstraSP[g.V()]; for (int v = 0; v < g.V(); v++) this._all[v] = new DijkstraSP(g, v); }
public Arbitrage(EdgeWeightedDigraph g, int source) { _g = g; _source = source; }
public CPM(EdgeWeightedDigraph g, int source) { _g = g; _source = source; }
public void TestEdgeWeightedDigraph() { EdgeWeightedDigraph g = new EdgeWeightedDigraph(9); g.AddEdge(new DirectedEdge(0, 2, 0.26d)); g.AddEdge(new DirectedEdge(0, 4, 0.38d)); g.AddEdge(new DirectedEdge(2, 7, 0.34d)); g.AddEdge(new DirectedEdge(3, 6, 0.52d)); g.AddEdge(new DirectedEdge(4, 5, 0.35d)); g.AddEdge(new DirectedEdge(5, 1, 0.32d)); g.AddEdge(new DirectedEdge(7, 3, 0.39d)); Debug.WriteLine(g); }