private void solve(IDirectedGraph g) { result = new List <int>(); Degrees degrees_info = new Degrees(g); int[] degrees = new int[g.V]; for (int i = 0; i < g.V; ++i) { degrees[i] = degrees_info.InDegree(i); } Queue <int> starts = new Queue <int>(); foreach (Int32 s in degrees_info.Sources()) { starts.Enqueue(s); } //只要还有顶点 while (starts.Count > 0) { Int32 v = starts.Dequeue(); result.Add(v); foreach (var w in g.Adj(v)) { //删除这个顶点的指出的边,因为这个顶点已经被删除了 --degrees[w]; if (degrees[w] == 0) { //下一个拓扑排序的顺序 starts.Enqueue(w); } } } }
private void dfs(IDirectedGraph digraph, int v) { onStack[v] = true; marked[v] = true; foreach (int w in digraph.Adj(v)) { if (HasCycle()) { return; } else if (!marked[w]) { edgeTo[w] = v; dfs(digraph, w); } else if (onStack[w])//如果访问过且在一个路径中 { cycle = new Stack <int>(); for (int x = v; x != w; x = edgeTo[x]) { cycle.Push(x);//把前驱放入栈中直到环的起点的后继 } cycle.Push(w); cycle.Push(v);//为何从v开始呢?因为v->w是有连接的。此时栈顶和栈底都是一个 } } onStack[v] = false;//循环结束,不是一条栈上链的 }
private void dfs(IDirectedGraph g, int v) { marked[v] = true; id[v] = count; foreach (var w in g.Adj(v)) { if (!marked[w]) { dfs(g, w); } } }