/************************************************************/ /********************图的深度优先搜索***********************/ /********************用邻接矩阵来实现***********************/ /************************************************************/ #include <stdio.h> #include <stdlib.h> #define N 8 typedef char ElemType; static ElemType vertex[N]; static int edge[N][N]; int flag[N]; //用来标示每个结点是否遍历过 void CreatGraph(ElemType vertex[N],int edge[N][N]) { int i = 0,j = 0; char c; printf("请输入结点中存放的数据: "); scanf("%c",&c); while(i < N) { if(c == ' ') { break; } else { vertex[i++] = c; scanf("%c",&c); } } // printf("It has gone to here: "); printf("请输入图中各个边的状态,数字1表示有连接,数字0表示无连接: "); for( i = 0;i < N;i++ ) { for( j = i;j < N;j++ ) { printf(" %c--->%c的连接状态为:",vertex[i],vertex[j]); scanf("%d",&edge[i][j]); edge[j][i] = edge[i][j]; } } for( i = 0;i < N;i++ ) { flag[i] = 0; } for( i = 0;i < N;i++ ) { for( j = 0;j < N;j++ ) { printf("%d ",edge[i][j]); } printf(" "); } } void DepthFirstSearch(int i)//i为要开始的额结点i = 0为A开始 { int j = 0; printf("%c ",vertex[i]); flag[i] = 1; for(j = 0;j < N;j++) { if(flag[j] == 0 && edge[i][j] == 1) { DepthFirstSearch(j); } } } int main() { int x = 0;//x =0~7分别表示从第一个输入的结点~最后一个输入的结点开始遍历 CreatGraph(vertex,edge); printf("深度优先搜素的顺序为: "); DepthFirstSearch(x); return 0; }