第六章 6.5 图的遍历
深度优先搜索
采用邻接矩阵表示图的深度优先搜索遍历
#include<bits/stdc++.h> using namespace std; #define MaxInt 32767 #define MVNum 100 #define OK 1 bool visited[MaxInt]; typedef char VerTexType; typedef int ArcType; typedef int Status ; typedef struct{ VerTexType vexs[MVNum];//存储顶点 ArcType arcs[MVNum][MVNum];//邻接矩阵 int vexnum,arcnum;//图的当前顶点数和边数 }AMGraph; int LocateVex(AMGraph G,char v1) { for(int i = 0; i < G.vexnum ; i ++) { if(G.vexs[i] == v1-'0') return i; } } Status CreateUDN(AMGraph &G) { char v1,v2; int w,i,j; cin>>G.vexnum>>G.arcnum; //读入图的顶点和边数 for( i = 0; i < G.vexnum ; i ++) cin>>G.vexs[i]; for( i = 0; i < G.vexnum ; i ++) for( j = 0; j < G.vexnum ; j ++) G.arcs[i][j] = MaxInt;//初始化邻接矩阵,边的权值均置为极大值MaxInt for(int k = 0; k < G.arcnum ; k ++) { cin>>v1>>v2>>w;//输入一条边的顶点和权值 i = LocateVex(G,v1); j = LocateVex(G,v2); G.arcs[i][j] = G.arcs[j][i] = w; } return OK; } void DFS_AM(AMGraph G,int v) { cout<<v; visited[v] = true;//访问第v个顶点,并将标志数组置为true; int w; for(w = 0; w < G.vexnum ; w ++)//依次检查邻接矩阵v所在的行 { if(G.arcs[v][w] != 0&& !visited[w]) { DFS_AM(G,w); } } } int main() { AMGraph G; CreateUDN(G); DFS_AM(G,1); return 0; }
采用邻接表表示图的深度优先搜索遍历
#include<bits/stdc++.h> using namespace std; #define MVNum 100 bool visited[MVNum]; #define OK 0 typedef int OhterInfo; typedef int VerTexType; typedef int Status; typedef struct ArcNode{//边结点 int adjvex;//相邻顶点信息 struct ArcNode *nextarc;//下一条边的指针 OhterInfo info;//权值 }ArcNode; typedef struct VNode{//存储顶点信息 VerTexType data; ArcNode *firstarc;//第一条依附该顶点的边的指针 }VNode,AdjList[MVNum]; typedef struct{ AdjList vertice;//结构体数组 int vexnum,arcnum;//图的当前顶点数和边数 }ALGraph; int LocateVex(ALGraph G,char ch) { for(int i = 0; i < G.vexnum ; i ++) if(G.vertice[i].data == ch-'0') return i; } Status CreateUDG(ALGraph &G) { char v1,v2; ArcNode *p1,*p2; cin>>G.arcnum>>G.vexnum ;//读入总边数和总的顶点数 int i,j,w; for(i = 0; i < G.vexnum ; i ++) { cin>>G.vertice[i].data ; G.vertice[i].firstarc = NULL; } for(i = 0; i < G.arcnum ; i ++) { cin>>v1>>v2>>w; i = LocateVex(G,v1); j = LocateVex(G,v2); p1 = new ArcNode; p1->nextarc = G.vertice[i].firstarc ; p1->adjvex = j; p1->info = w; G.vertice[i].firstarc = p1; p2 = new ArcNode; p2->nextarc = G.vertice[j].firstarc ; p2->adjvex = i; p2->info = w; G.vertice[j].firstarc = p2; } return OK; } void DFS_AL(ALGraph G,int v) { cout<<v; int w; visited[v] = true; ArcNode *p; p = G.vertice[v].firstarc ;//p指向v的边链表的第一个边结点 while(p !=NULL)//边结点非空 { w = p->adjvex ; if(!visited[w])//如果未被访问,则递归调用 DFS_AL(G,w); p = p->nextarc ;//指向下一个边结点 } return; } int main() { ALGraph G; CreateUDG(G); DFS_AL(G,1); return 0; }