拓扑排序算法(C++实现)

bool Topological(int v[]) { //计算有向图中顶点的拓扑次序 //如果找到了一个拓扑次序,则返回true, 此时, 在v[0->n-1]中记录拓扑次序 //如果不存在拓扑次序,则返回false int n = Vertices(); //计算入度 int *InDegree = new int [n+1]; InitializePos(); for (int i = 1; i <= n; i++) InDegree[i] = 0; for (int i = 1; i <= n; i++) { int u = Begin(i); while (u) { InDegree[u]++; u = NextVertex(i); } } // 把入度为0的点压入栈 LinkedStack S; for (int i = 1; i <= n; i++) { if (!InDegree[i]) S.Add(i); } int i = 0; while (!S.IsEmpty()) { int w; S.Delete(w); v[i++] = w; int u = Begin(w); while (u) { //更新u的入度 InDegree[u]--; //如果u的入度为0, 则压入栈 if (!InDegree[u]) S.Add(u); u = NextVertex(w); } } DeactivatePos(); delete [] InDegree; return (i == n); } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kongbu0622/archive/2009/10/09/4647700.aspx

你可能感兴趣的:(C&C++)