// Graph,BFS
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
int graph[100][100]={0};
int visited[100]={0};
queue <int> q;
void Initgraph()
{
int n,i;
int p,q;
cout<<"Input the edge num:"<<endl;
cin>>n;
cout<<"Input the connected p and q:"<<endl;
for(i=0;i<n;i++)
{
cin>>p>>q;
graph[p][q]=graph[q][p]=1;
}
}
void visit(int v)
{
cout<<v<<" ";
}
int getneighbor(int v)
{
int i;
for(i=0;i<100;i++)
{
if(graph[v][i]==1)
if(!visited[i])
{
return i;
}
}
return -1;
}
void BFS(int v)
{
cout<<"BFS sequence:"<<endl;
visit(v);
visited[v]=1;
q.push(v);
while(!q.empty())
{
int u=q.front();
q.pop();
int w=getneighbor(u);
while(w!=-1)
{
visit(w);
visited[w]=1;
q.push(w);
w=getneighbor(u);
}
}
}
int main()
{
Initgraph();
cout<<"Please input the start vex:"<<endl;
int v;
cin>>v;
BFS(v);
return 0;
}图——广度优先遍历(邻接矩阵存储)
图的广度优先搜索(BFS)实现
最新推荐文章于 2024-03-13 15:38:05 发布
本文介绍了一种使用C++实现图的广度优先搜索(BFS)的方法,包括图的初始化、节点访问及遍历过程。通过用户输入边的数量和连接的顶点来构建图,并展示BFS的遍历顺序。
3390

被折叠的 条评论
为什么被折叠?



