鄰接表建圖及其深度與廣度遍歷
阿新 • • 發佈:2020-07-28
#include<iostream> #include<queue> #include<memory.h> #define maxSize 100 using namespace std; struct edgeNode { int dest; //鄰接頂點的陣列下標 //int weight; 權重 edgeNode* next; }; struct vertexNode { char vertex; edgeNode* link; }; class Graph { private: int vertexNum,edgeNum; vertexNode adjTable[maxSize];int visited[maxSize]; public: Graph(char a[],int vn,int en) { vertexNum=vn; edgeNum=en; for(int i=0; i<vertexNum; i++) { adjTable[i].vertex=a[i]; adjTable[i].link=NULL; visited[i]=0; } } int getVertexIndex(charv) { for(int i=0; i<vertexNum; i++) { if(adjTable[i].vertex==v) { return i; } } return -1; } void insertEdge(char v1,char v2) { int index1=getVertexIndex(v1); int index2=getVertexIndex(v2); edgeNode* p=new edgeNode(); p->dest=index2; p->next=adjTable[index1].link; adjTable[index1].link=p; } void show() { cout<<"鄰接表為:"<<endl; for(int i=0; i<vertexNum; i++) { cout<<adjTable[i].vertex; edgeNode* p=adjTable[i].link; while(p!=NULL) { cout<<"->"; cout<<adjTable[p->dest].vertex; p=p->next; } cout<<endl; } } void DFS(char v) { int index=getVertexIndex(v); cout<<adjTable[index].vertex; visited[index]=1; edgeNode* p=adjTable[index].link; while(p!=NULL) { if(visited[p->dest]==0) { DFS(adjTable[p->dest].vertex); } p=p->next; } } void BFS(char v) { memset(visited,0,sizeof(visited)); //將viseted[]中元素初始化為0 int index=getVertexIndex(v); queue<int> Q; //下標進佇列 cout<<adjTable[index].vertex; visited[index]=1; Q.push(index); while(!Q.empty()) { index=Q.front(); Q.pop(); edgeNode* p=adjTable[index].link; while(p!=NULL) { if(visited[p->dest]==0) { cout<<adjTable[p->dest].vertex; visited[p->dest]=1; Q.push(p->dest); } p=p->next; } } } }; int main() { cout<<"請輸入圖的頂點數、邊數:"; int vn,en; cin>>vn>>en; cout<<"請輸入各個頂點:"; char a[vn]; for(int i=0; i<vn; i++) { cin>>a[i]; } Graph G(a,vn,en); cout<<"請輸入各條邊:"<<endl; char v1,v2; for(int i=0; i<en; i++) { cin>>v1>>v2; G.insertEdge(v1,v2); } G.show(); cout<<"請輸入遍歷起始頂點:"; char init; cin>>init; cout<<"深度遍歷:"; G.DFS(init); //先確保viseted[]已初始化歸零 cout<<endl; cout<<"廣度遍歷:"; G.BFS(init); //先確保visited[]已初始化歸零 cout<<endl; return 0; } //請輸入圖的頂點數、邊數:4 10 //請輸入各個頂點:a b c d //請輸入各條邊: //a b //a c //a d //b a //b c //c b //c a //c d //d c //d a //鄰接表為: //a->d->c->b //b->c->a //c->d->a->b //d->a->c //請輸入遍歷起始頂點:b //深度遍歷:bcda //廣度遍歷:bcad