标签:
队列实现广度优先遍历
#include <iostream> #include <queue> using namespace std; int visit[5]={0}; typedef struct { char vexs[5]; int AdjMatrix[5][5]; int vexnum; }Graph; Graph g={ {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘}, { 0,1,0,1,0, 1,0,1,0,1, 0,0,0,1,1, 1,0,0,0,0, 0,1,1,0,0 } , 5 }; queue<int> list;; int BFS(Graph *g,int nowVex){ if(visit[nowVex]==0) cout<<"visit "<<g->vexs[nowVex]<<" "; visit[nowVex]=1; if(list.size()!=0) list.pop(); for(int i=0;i<g->vexnum;i++) { if(g->AdjMatrix[nowVex][i]==1&&visit[i]==0) { list.push(i); // cout<<"nowVex "<<nowVex<<" push "<<g->vexs[i]<<endl; } } while(list.size()!=0){ // cout<<" list front is "<<g->vexs[list.front()]<<endl; BFS(g,list.front()); } return 0; } int main() { BFS(&g,0); }
标签:
原文地址:http://www.cnblogs.com/lxdonge/p/4549417.html