数据结构C语言版之邻接矩阵(遍历)
//邻接矩阵: #include<stdio.h> #include<stdlib.h> #define MAX_VERTE_NUM 20 #define Stack_size 100 #define Stackincreament 10 int visited[MAX_VERTE_NUM]; typedef int AdjMatrix[MAX_VERTE_NUM][MAX_VERTE_NUM]; typedef struct{ char vex[MAX_VERTE_NUM]; AdjMatrix arc; int vexnum,arcnum; }MGraph; typedef struct{ int start; int end; }elemtype; typedef struct{ elemtype *base; int top; int stacksize; }sqstack; void initstack(sqstack &s) { s.base=(elemtype*)malloc(Stack_size*sizeof(elemtype)); s.stacksize=Stack_size; if(!s.base) exit(0); s.top=0; } void push(sqstack &s,elemtype e) { if(s.top>=s.stacksize) { s.base=(elemtype*)realloc(s.base,(Stack_size+Stackincreament)*sizeof(elemtype)); if(!s.base) exit(0); s.stacksize+=Stackincreament; } s.base[s.top++]=e; } void pop(sqstack &s,elemtype &e) { if(s.top==0) return ; e=s.base[--s.top]; } int stackempty(sqstack s) { if(s.top==0) return 1; return 0; } int Locate(MGraph &G,char v) { int i=0; for(i=0;i<G.vexnum;i++) if(G.vex[i]==v) return i; return -1; } void CreatGraph(MGraph &G) { int m,n,i,j; char v1,v2; printf("请输入图的顶点数和边数:\n"); scanf("%d",&G.vexnum); scanf("%d",&G.arcnum); getchar(); printf("请输入各个顶点:\n"); for(int k=0;k<G.vexnum;k++) scanf("%c",&G.vex[k]); getchar(); for(i=0;i<G.vexnum;i++) for(j=0;j<G.vexnum;j++) G.arc[i][j]=0; printf("请输入边: \n"); for(k=0;k<G.arcnum;k++) { scanf("%c%c",&v1,&v2); getchar(); m=Locate(G,v1); n=Locate(G,v2); G.arc[m][n]=G.arc[n][m]=1; } } void ShowAdjMatrix(MGraph G) { for(int i=0;i<G.vexnum;i++) { for(int j=0;j<G.vexnum;j++) printf("%3d",G.arc[i][j]); printf("\n"); } } int FirstAdjVex(MGraph G,int v) { int i; for(i=0;i<G.vexnum;i++) if(G.arc[v][i]==1) return i; return -1; } int NextAdjVex(MGraph G,int v,int w) { int j; for(j=w+1;j<G.vexnum;j++) if(G.arc[v][j]==1) return j; return -1; } void DFS(MGraph G,int v) { elemtype elem; int w; sqstack s; visited[v]=1; printf("%c",G.vex[v]); initstack(s); w=FirstAdjVex(G,v); while(!stackempty(s)||w>=0) { while(w>=0) { if(visited[w]==1) { w=NextAdjVex(G,v,w); } else { printf("%c",G.vex[w]); visited[w]=1; elem.start=v; elem.end=w; push(s,elem); v=w;w=FirstAdjVex(G,v); } } if(!stackempty(s)) { pop(s,elem); v=elem.start; w=elem.end; v=NextAdjVex(G,v,w); } } } void DFStraverse(MGraph G) {//递归深度优先遍历 int v; for(v=0;v<G.vexnum;v++) visited[v]=0; for(v=0;v<G.vexnum;v++) if(!visited[v]) DFS(G,v); } int main() { MGraph G; CreatGraph(G); ShowAdjMatrix(G); DFStraverse(G); printf("\n"); return 0; }
不为失败找原因,要为成功找方法!