#include "stdafx.h" #include "stdio.h" #include "stdlib.h" #define MAX_VERTEX_NUM 11 //頂點的最大數 #define INFINITY 32768 #define Error 0 #define OK 1 typedef enum{DG,DN,UDG,UDN} GraphKind; //圖的種類 G表示有向圖, DN表示有向網, UDG表示無向圖, UDN表示無向網 typedef char VertexData; typedef struct ArcNode { int adj; }ArcNode; typedef struct { VertexData vexs[MAX_VERTEX_NUM]; //頂點向量 ArcNode arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //鄰接矩陣 int vexnum,arcnum; //圖的頂點 和 弧數 GraphKind kind ; }AdjMatrix; int LocateVertex(AdjMatrix *G, VertexData v) //求頂點的位置座標 { int j = Error , k; for(k=0; k< G->vexnum; k++) if( G->vexs[k] == v) { j = k; break; } return j; } int CreateDN(AdjMatrix *G) { int i,j,k,weight; VertexData v1,v2; printf("請輸入頂點的個數和弧數"); scanf("%d%d",&G->vexnum,&G->arcnum); for(i =0; i<G->vexnum;i++) //初始化 for(j=0;j<G->vexnum;j++) G->arcs[i][j].adj = INFINITY ; for(i=0;i<G->vexnum;i++) { printf("請輸入圖的頂點\n"); fflush(stdin); scanf("%c",&G->vexs[i]); } for(k=0;k<G->arcnum;k++) { printf("請輸入一條弧的兩個頂點及權值"); fflush(stdin); scanf("%c,%c,%d",&v1,&v2,&weight); i = LocateVertex(G,v1); j = LocateVertex(G,v2); G->arcs[i][j].adj = weight; //創建弧 } return OK; } void FindID(AdjMatrix G,int indegree[]) { int i,j; for(i=0;i<G.vexnum;i++) for(j=0;j<G.vexnum;j++) if(G.arcs[i][j].adj !=32768) indegree[j] ++; } bool TopSort(AdjMatrix G) { int stack[100] = {0}; int top=0; int indegree[50]={0}; int i,j,count,p; FindID(G,indegree); for(i=0;i<G.vexnum;i++) if(indegree[i] == 0) stack[top++] = i; count = 0; while(top!=0) { i = stack[--top]; printf("%c ",G.vexs[i]); count ++ ; for( p = -1,j = 0 ;j<G.vexnum;j++) //找第一個鄰接點 if(G.arcs[i][j].adj != 32768) { p = j; break; } while( p != -1) { indegree[p] --; if( indegree[p] == 0) stack[top++] = p; for( j = p+1 ;j<G.vexnum;j++) //找下一個鄰接點 if(G.arcs[i][j].adj != 32768) {p = j; break;} if( j == G.vexnum ) p = -1; //未找到 } } // while return count < G.vexnum ? Error: OK ; } int _tmain(int argc, _TCHAR* argv[]) { AdjMatrix G; CreateDN(&G); if(!TopSort(G)) printf("\n存在迴路!\n"); return 0; }