深度优先搜索 (DFS)
//基于邻接矩阵的 DFS #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define MAXV 100 //最大顶点数 //邻接矩阵的图类型定义 typedef struct{ char Vex[MAXV]; //顶点表 int Edge[MAXV][MAXV]; //边表 int vexnum,edgenum; //顶点数,边数 }MGraph; bool visited[MAXV]; //访问标记数组 //访问顶点u void visit(MGraph G,int u){ printf("%c ",G.Vex[u]); } //深度优先遍历 void DFS(MGraph G,int u){ visit(G,u); //访问顶点u visited[u]=true; //标记u已访问 for(int v=1; v<=G.vexnum; v++){ if(!visited[v]&&G.Edge[u][v]==1) DFS(G,v); //递归访问v } } //对图G进行深度优先遍历 void DFSTraverse(MGraph G){ for(int u=1; u<=G.vexnum; ++u){ if(!visited[u]) DFS(G,u); //递归访问u } } int main(){ MGraph G; G.vexnum=5; G.edgenum=4; char s[]={'A','B','C','D','E'}; for(int i=1;i<=G.vexnum;i++){ G.Vex[i]=s[i-1]; } G.Edge[1][2]=1; //AB G.Edge[1][3]=1; //AC G.Edge[2][5]=1; //BE G.Edge[2][4]=1; //BD DFSTraverse(G); return 0; }
//基于邻接表的 DFS #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define MAXV 100 //最大顶点数 //边结点的定义 typedef struct ArcNode{ int adjvex; //邻接点的下标 // int weight; //边的权值 struct ArcNode *next; //指向下一个边结点 } ArcNode; //顶点结点的定义 typedef struct{ char data; //顶点信息 ArcNode *first; //指向该顶点的第一个边结点 } VexNode,AdjList[MAXV]; //邻接表的图类型定义 typedef struct{ AdjList adjList; //邻接表 int vexnum,arcnum; //顶点数,边数 } ALGraph; bool visited[MAXV]; //访问标记数组 //访问顶点u void visit(ALGraph G,int u){ printf("%c ",G.adjList[u].data); } //深度优先遍历 void DFS(ALGraph G,int u){ visit(G,u); //访问顶点u visited[u]=true; //标记u已访问 for(ArcNode *p=G.adjList[u].first; p; p=p->next){ int v=p->adjvex; //取得邻接点v if(!visited[v]) DFS(G,v); //递归访问v } } //对图G进行深度优先遍历 void DFSTraverse(ALGraph G){ for(int u=1; u<=G.vexnum; ++u){ if(!visited[u]) DFS(G,u); //递归访问u } } int main(){ ALGraph G; G.vexnum=5; G.arcnum=4; char s[]={'A','B','C','D','E'}; for(int i=1;i<=G.vexnum;i++){ G.adjList[i].data=s[i-1]; G.adjList[i].first=NULL; //必须的 } ArcNode *p=(ArcNode*)malloc(sizeof(ArcNode)); G.adjList[1].first=p; p->adjvex=2; //AB p=(ArcNode*)malloc(sizeof(ArcNode)); G.adjList[1].first->next=p; p->adjvex=3; //AC p=(ArcNode*)malloc(sizeof(ArcNode)); G.adjList[2].first=p; p->adjvex=5; //BE p=(ArcNode*)malloc(sizeof(ArcNode)); G.adjList[2].first->next=p; p->adjvex=4; //BD DFSTraverse(G); return 0; }
.
浙公网安备 33010602011771号