采用邻接矩阵存储
#include <queue>
queue <int> q;
bool visited[MAXVEX];
void BFSTraverse(MGraph G) {
int i, j;
for(i = 0; i < G.vexnum; i++)
visited[i] = false;
for(i = 0; i < G.vexnum; i++) {
if(!visited[i]) {
visited[i] = true;
cout<<G.vexs[i]<<" ";
q.push(i);
while(!q.empty()) {
i = q.front();
q.pop();
for(j = 0; j < G.vexnum; j++) {
if(G.arc[i][j] == 1 && !visited[j]) {
visited[j] = true;
cout<<G.vexs[j]<<" ";
q.push(j);
}
}
}
}
}
}
采用邻接表存储
#include <queue>
queue <int> q;
bool visited[MAXVEX];
void BFSTraverse(ALGraph G) {
int i, j;
for(i = 0; i < G.vexnum; i++)
visited[i] = false;
arcNode *p;
for(i = 0; i < G.vexnum; i++) {
if(!visited[i]) {
visited[i] = true;
cout<<G.adjlist[i].data<<" ";
q.push(i);
while(!q.empty()) {
i = q.front();
q.pop();
p = G.adjlist[i].first;
while(p) {
if(!visited[p->adjvex]) {
visited[p->adjvex] = true;
cout<<G.adjlist[p->adjvex].data<<" ";
q.push(p->adjvex);
}
p = p->next;
}
}
}
}
}