1.编一C程序,它能根据读入的数据构造有向图G,并输出G的DFS遍历序列(从V0开始),
图的输入形式为n V0 Vi0 V1 Vi1 V2 Vi2...Vi Vin -1 -1(-1,-1为输入结束标记,其他的值都>=0且
它们都是整数,且100>n>0。(注:程序的可执行文件名必须是 e2.exe,存于你的帐号或其debug目录下。)
输入: 9 0 1 0 2 0 7 1 2 1 4 2 3 3 5 3 6 4 3 4 5 7 8 8 6 -1 -1node
#include<stdio.h> #define MAX 100 typedef enum{False,True} Boolean; int G[MAX][MAX]; int n; //创建图的邻接矩阵G[][] void GreateG(){ int i,j; printf("Input the number of the node:"); scanf("%d", &n); printf("\n"); for(i=0;i<n;i++){ for(j=0;j<n;j++){ G[i][j]=0; } } do{ scanf("%d%d", &i,&j); G[i][j]=1; }while((i!=-1) && (j!=-1)); } //拓扑排序,输出拓扑序列 void TopSort(){ int i,j; //按照无前驱顶点优先思想,degree[]存放个节点的入度 int degree[100]; Boolean visited[MAX],flag=True; printf("The Topolgical Order as follow:"); for(i=0;i<n;i++){ degree[i]=0; visited[i]=False; } printf("\n"); while(flag==True){ for(i=0;i<n;i++){ for(j=0;j<n;j++){ degree[i]=G[j][i]+degree[i]; } } i=0; //最早输出入度为0的顶点 while((i<n) && (degree[i]!=0) || visited[i]==True){ i++; } //全部节点均已输出结束,不然说明存在环,无拓扑序列 if(i<n){ printf("%d",i); visited[i]=True; for(j=0;j<n;j++){ G[i][j]=0; degree[j]=0; } }else{ flag = False; } } } void main(){ GreateG(); TopSort(); printf("\n"); }