bfs 广度优先搜索

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/chu_jian86a/article/details/51146912
#include "iostream"  
#include "cstdio"
#include "cstring"
#include "queue"
#define max 100  
#define INF 99999  
using namespace std;    
int count,have_edge[max][max];  
bool visited[max];  
//图的存储(邻接矩阵)  
void graph()  
{ 
    cout<<"请输入总结点数:"<<endl;
	cin>>count; 
    int m,n;  
    cout<<"请输入具有关系的各顶点,以“-1 -1 ”作为结束标志:"<<endl;   
    while(cin>>m>>n&&m!=-1&&n!=-1)  
    {
    	have_edge[m][n]=1; 
    	have_edge[n][m]=1;
	} 
}   
  
int firstadj(int v)  
{  
    for(int w=1;w<=count;w++)  
        if(have_edge[v][w])  
            return w;  
    return 0;  
}  
int nextadj(int v,int w)  
{  
    for(w=w+1;w<=count;w++)  
        if(have_edge[v][w])  
            return w;  
    return 0;  
}
int visite(int v)
{
	cout<<v<<" ";
	return 0;
}
void bfs(int v)
{
	int w;
	queue <int> Q;
	visite(v);
	visited[v]=true;
	Q.push(v);
	while(!Q.empty())
	{
		int v1=Q.front();
		Q.pop();
		w=firstadj(v1); 
		while(w!=0)//依次访问未被访问的邻接点
		{
			if(!visited[w])
			{
				visite(w);
				visited[w]=true;
				Q.push(w);
			}
			w=nextadj(v1,w);
		} 
	}
}
void travel_dfs()
{
	int i;
	memset(visited,0,sizeof(visited));
	for(int i=1;i<=count;i++)
	    if(!visited[i])
	        bfs(i);
}
int main()
{
	graph();
	int v0;
	cout<<"请输入起始结点:"<<endl;
	cin>>v0; 
	bfs(v0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/chu_jian86a/article/details/51146912

相关文章