图的广度优先遍历/C++
图的广度优先遍历
BFS 函数实现代码
void BFS(Graph g,int startVex,int targerVex,int *visited){
Q.push(startVex);
visited[startVex]=1;
while(!Q.empty()){
int next=Q.front();
Q.pop();
cout<<" "<<g->vertex[next].element;
node nd =g->vertex[next].next;
while(nd){
if(!visited[nd->nextVex]){
Q.push(nd->nextVex);
visited[nd->nextVex]=1;
}
nd=nd->next;
}
}
}
由于其特殊性,我们需要借助队列
queue<int> Q;
main函数
int main(){
Graph graph= Create();
for (int c= 'A';c<='E';++c)
addVex(graph,(char)c);
addEdge(graph,'A','B');
addEdge(graph,'B','C');
addEdge(graph,'B','E');
addEdge(graph,'C','D');
addEdge(graph,'D','E');
int arr[graph->vex];
for(int i=0;i<=graph->vex;i++) arr[i]=0;
BFS(graph,0,4,arr);
return 0;
}