资源描述:
《数据结构C语言版-图的建立与遍历.docx》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、/*-----------------------------------------------------数据结构C语言版——图的建立与遍历编程环境VC++6.0Damon2012年4月26号------------------------------------------------------*/#include#include#include#include#definenull0#defineTRUE1#defineFALSE0#defineOVERFLOW-2#defineOK1
2、#defineERROR0typedefintStatus;//图的邻接矩阵——数组存储表示-------------------------#defineINFINITYINT_MAX#defineMAX_VERTEX_NUM20typedefintVRType;typedefcharVertexType[20];typedefintBoolean;typedefstructArcCell{VRTypeadj;//InfoType*info;}ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];typedefstruct{
3、VertexTypevexs[MAX_VERTEX_NUM];AdjMatrixarcs;intvexnum,arcnum;}MGraph;/*图的临接表存储表示------------------------------------typedefstructArcNode{intadjvex;structArcNode*nextarc;InfoType*info;}ArcNode;typedefstructVNode{VertexTypedata;ArcNode*firstarc;}VNode,AdjList[MAX_VERTEX_NUM];typedefstruct{
4、AdjListvertices;intvexnum,arcnum;intkind;}ALGraph;*///采用数组(邻接矩阵)表示法,构造无向图G--------------intLocateVex(MGraph*G,VertexTypev);intCreateGraph(MGraph*G){inti,j,k;VertexTypev1,v2;printf("请依次输入无向网的顶点数和弧数:");scanf("%d%d",&G->vexnum,&G->arcnum);printf("请输入%d顶点向量:",G->vexnum);for(i=0;ivexnum;
5、i++){scanf("%s",G->vexs[i]);}printf("顶点列表:");for(i=0;ivexnum;i++)puts(G->vexs[i]);for(i=0;ivexnum;i++)for(j=0;jvexnum;j++){G->arcs[i][j].adj=0;}printf("请输入%d条弧关系的邻接矩阵:",G->arcnum);for(k=0;karcnum;k++){scanf("%s%s",v1,v2);i=LocateVex(G,v1);j=LocateVex(G,v2);G->arcs[i]
6、[j].adj=1;G->arcs[j][i]=G->arcs[i][j];}return(1);}intLocateVex(MGraph*G,VertexTypev){inti;for(i=0;i<=G->vexnum;i++){if(strcmp(v,G->vexs[i])==0)break;}return(i);}//查找第一个邻接点---------------------intFirstAdjVex(MGraph*G,intv){intj,p=-1;for(j=0;jvexnum;j++)if(G->arcs[v][j].adj==1){p=j;brea
7、k;}return(p);}//查找下一个邻接点-----------------------intNextAdjVex(MGraph*G,intv,intw){intj,p=-1;for(j=w+1;jvexnum;j++)if(G->arcs[v][j].adj==1){p=j;break;}return(p);}//按邻接矩阵方式输出无向图----------voidPrintGraph(MGraph*G){inti,j;printf("无向图为:");for(i=0;ivexnum;i++){p