標籤:
/*-----------------------------------------------*//* 鄰接矩陣的DFS */// 基於 資料結構(14) 中的鄰接矩陣的結構 #include <iostream>using namespace std;typedef char VertexType;typedef int EdgeType;const int MAXVEX = 100;const int INFINITY = 65535;typedef struct{ VertexType vexs[MAXVEX]; EdgeType arc[MAXVEX][MAXVEX]; int numVertexes, numEdges;} MGraph;void CreateMGraph(MGraph &G){ int i,j,k,w; cout<<"輸入頂點數和邊數:"; cin>>G.numVertexes>>G.numEdges; cout<<"輸入頂點資訊: "<<endl; for(i=0;i<G.numVertexes;i++) cin>>G.vexs[i]; for(i=0;i<G.numVertexes;i++) for(j=0;j<G.numVertexes;j++) G.arc[i][j] = INFINITY; for(k=0;k<G.numEdges;k++) { cout<<"輸入邊(vi,vj)上的下標i,下標j和權w:"<<endl; cin>>i>>j>>w; G.arc[i][j] = w; G.arc[j][i] = G.arc[i][j]; }}/*-----------------------------------------------*/// DFSbool visit[MAXVEX]; // 用於標記頂點是否已被遍曆 void DFS(MGraph G, int i) // DFS搜尋 { int j; visit[i] = true; // 當前頂點標記為 已遍曆 cout<<G.vexs[i]<<ends; // 輸出頂點資訊(可改為其他動作) for(j=0;j<G.numVertexes;j++) // 遍曆與當前頂點有聯絡的其他頂點 if(G.arc[i][j] == 1 && !visit[j]) DFS(G,j); // 遞迴 }// DFSTraverse void DFSTraverse(MGraph G){ int i; for(i=0;i<G.numVertexes;i++) // 初始化標記數組為 未遍曆 visit[i] = false; for(i=0;i<G.numVertexes;i++) // 對每一個沒有遍曆過的頂點進行DFS if(!visit[i]) DFS(G,i);}int main(){ MGraph G; CreateMGraph(G); DFSTraverse(G); return 0;}
/*-----------------------------------------------*//* 鄰接表的DFS */// 基於 資料結構(14) 中的鄰接表的結構 #include <iostream>using namespace std;const int MAXVEX = 100;typedef char VertexType;typedef int EdgeType;typedef struct EdgeNode{ int adjvex; EdgeType weight; struct EdgeNode *next; } EdgeNode;typedef struct VertexNode{ VertexType data; EdgeNode *firstedge;} VertexNode, AdjList[MAXVEX];typedef struct{ AdjList adjList; int numVertexes, numEdges;} GraphAdjList;void CreateALGraph(GraphAdjList &G){ int i,j,k,w; EdgeNode *e; cout<<"輸入頂點數和邊數:"; cin>>G.numVertexes>>G.numEdges; cout<<"輸入各頂點的資訊:"<<endl; for(i=0;i<G.numVertexes;i++) { cin>>G.adjList[i].data; G.adjList[i].firstedge = NULL; } for(k=0;k<G.numEdges;k++) { cout<<"輸入邊(vi,vj)上的頂點序號:"<<endl; cin>>i>>j>>w; e = new EdgeNode; e->adjvex = j; e->weight = w; e->next = G.adjList[i].firstedge; G.adjList[i].firstedge = e; e->adjvex = i; e->weight = w; e->next = G.adjList[j].firstedge; G.adjList[j].firstedge = e; }}/*-----------------------------------------------*/// DFSbool visit[MAXVEX]; // 用於標記頂點是否已被遍曆void DFS(GraphAdjList GL, int i) // DFS搜尋{ EdgeNode *p; visit[i] = true; // 當前頂點標記為 已遍曆 cout<<GL.adjList[i].data<<ends; // 輸出頂點資訊(可改為其他動作) p = GL.adjList[i].firstedge; // 指向當前鄰接頂點 指向的子結點 while(p) { if(!visit[p->adjvex]) // 遍曆與當前鄰接頂點有聯絡的 其他頂點 DFS(GL,p->adjvex); p = p->next; // 繼續遍曆下一個子結點 }}void DFSTraverse(GraphAdjList GL){ int i; for(i=0;i<GL.numVertexes;i++) // 初始化標記數組為 未遍曆 visit[i] = false; for(i=0;i<GL.numVertexes;i++) // 對每一個沒有遍曆過的頂點進行DFS if(!visit[i]) DFS(GL,i);}int main(){ GraphAdjList G; CreateALGraph(G); DFSTraverse(G); return 0;}
資料結構(15):圖 深度優先遍曆(DFS)