/*树的邻接矩阵的存储结构*/ #include <stdio.h> #include <stdlib.h> #define MAXVEX 10 #define InitEdge 0 typedef char VertexType; typedef int EdgeType; typedef struct MGraph { VertexType vex[MAXVEX]; EdgeType arc[MAXVEX][MAXVEX]; int numVertexes; int numEdges; }MGraph; static int Flag[MAXVEX]; void CreateMGraph(MGraph *G) { int i = 0,j = 0,k = 0,w = 0,m = 0,n = 0; char c; printf("请输入顶点数和边数,之间用逗号隔开 : "); fflush(stdin); scanf("%d,%d",&(G->numVertexes),&(G->numEdges)); printf("请输入顶点的值 : "); fflush(stdin); scanf("%c",&c); while(i < G->numVertexes) { if(c == ' ') break; G->vex[i++] = c; scanf("%c",&c); } //邻接矩阵的初始化 for(i = 0;i < G->numVertexes;i++) //邻接矩阵的初始化,初始化为0 { for(j = 0;j < G->numVertexes;j++) { G->arc[i][j] = InitEdge; } } for(i = 0;i < G->numVertexes;i++) //标识数组的初始化,0表示未访问过 { Flag[i] = 0; } fflush(stdin); for(m = 0,n = 0,k = 0; k < G->numEdges; k++) { printf("请输入边(Vi~Vj)的顶点下标i和j,以及权重w: "); scanf("%d,%d,%d",&m,&n,&w); G->arc[m][n] = w; G->arc[n][m] = G->arc[m][n]; } printf(" 结点中存放的数据为 : "); for(i = 0;i < G->numVertexes;i++) { printf("%c ",G->vex[i]); } printf(" 您输入的邻接矩阵为: "); for(i = 0;i < G->numVertexes;i++) //输出邻接矩阵方便查看输入是否有误 { for(j = 0;j < G->numVertexes;j++) { printf("%d ",G->arc[i][j]); } printf(" "); } printf(" 标示数组的值初始化为 : "); for(i = 0;i < G->numVertexes;i++) { printf("%d ",Flag[i]); } } void DepthFirstSearch(MGraph *G,int i) { int j = 0; if(Flag[i] == 0) { printf("%c ",G->vex[i]); } Flag[i] = 1; for(j = 0;j < G->numVertexes;j++) { if((G->arc[i][j]) != InitEdge && 0 == (Flag[j])) { DepthFirstSearch(G,j); } } } int main() { int k = 0; //设置从邻接矩阵的第几行开始DFS搜索,这里从第1行开始 struct MGraph *G; CreateMGraph(G); printf(" ********************************************** "); printf("DFS的排序结果为: "); DepthFirstSearch(G,k); printf(" ********************************************** "); return 0; }