private void Dfs(EdgeWeightedDigraph G, int v)//(加权有向图)寻找相连的顶点 { onStack[v] = true; marked[v] = true; foreach (DirectedEdge w in G.Adj(v)) { if (this.HasCycle()) { return; } else if (!marked[w.To()]) { edgeTo[w.To()] = v;//存储最先到达w.To()点的v点 Dfs(G, w.To()); } else if (onStack[w.To()]) { cycle = new Stack <int>(); for (int x = v; x != w.To(); x = edgeTo[x]) { cycle.Push(x); } cycle.Push(w.To()); cycle.Push(v); } } onStack[v] = false; }
private void Relax(EdgeWeightedDigraph G, int v) { foreach (DirectedEdge e in G.Adj(v)) { int w = e.To(); if (distTo[w] > distTo[v] + e.Weight()) { distTo[w] = distTo[v] + e.Weight(); edgeTo[w] = e; } } }
private void Dfs(EdgeWeightedDigraph G, int v) { pre.enqueue(v); marked[v] = true; foreach (DirectedEdge w in G.Adj(v)) { if (!marked[w.To()]) { Dfs(G, w.To()); } } post.enqueue(v); reversePost.Push(v); }
private void Relax(EdgeWeightedDigraph G, int v) { foreach (DirectedEdge e in G.Adj(v)) {// v->w e:v和w相连的边 int w = e.To(); if (distTo[w] > distTo[v] + e.Weight()) {// 起点到达w点的路径 > 起点到达v的路径+e的权重 distTo[w] = distTo[v] + e.Weight(); edgeTo[w] = e; if (pq.Contains(w)) { pq.Change(w, distTo[w]); } else { pq.Insert(w, distTo[w]); } } } }
private void Relax(EdgeWeightedDigraph G, int v) { foreach (DirectedEdge e in G.Adj(v)) { int w = e.To(); if (distTo[w] > distTo[v] + e.Weight()) { distTo[w] = distTo[v] + e.Weight(); edgeTo[w] = e; if (!onQ[w]) { queue.enqueue(w); onQ[w] = true; } } if (cost++ % G.VNumber() == 0) { FindNegativeCycle();//寻找有向图中是否有负权重环,以保证循环能够结束 } } }