#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; }
本文出自 “black4yL” 博客,请务必保留此出处http://black4yl.blog.51cto.com/4222963/1581632
原文地址:http://black4yl.blog.51cto.com/4222963/1581632