拓扑排序C++代码来一份
时间: 2023-03-13 12:30:34 浏览: 129
拓扑排序C的代码如下:
#include <stdio.h>
#define MAXV 100 /* maximum number of vertices */
int n; /* number of vertices in the graph */
int AdjMatrix[MAXV+1][MAXV+1];
int indegree[MAXV+1];
void TopologicalSort(void);
int main(void)
{
int i,j,count;
/* read the adjacency matrix */
scanf("%d",&n);
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
scanf("%d",&AdjMatrix[i][j]);
/* find the indegree of each vertex */
for (j=1; j<=n; j++) {
count = 0;
for (i=1; i<=n; i++)
count += AdjMatrix[i][j];
indegree[j] = count;
}
TopologicalSort();
return 0;
}
void TopologicalSort(void)
{
int i,j,k;
int top=-1; /* points to the top element of stack */
int S[MAXV+1]; /* S[top] is the current vertex */
int v; /* current vertex */
int output[MAXV+1]; /* output sequence */
int outputIndex=0; /* index for output sequence */
/* initialize stack */
for (i=1; i<=n; i++)
if (indegree[i] == 0)
S[++top] = i;
/* start loop */
while (top != -1) {
v = S[top--];
output[outputIndex++] = v;
/* remove vertex v from graph */
for (j=1; j<=n; j++)
if (AdjMatrix[v][j] == 1) { /* vertex j is adjacent to v */
indegree[j]--;
if (indegree[j] == 0)
S[++top] = j;
} /* end of for */
} /* end of while */
/* print output sequence */
for (i=0; i<n; i++)
printf("%d ",output[i]);
printf("\n");
}
阅读全文