图——广度优先遍历(邻接矩阵存储)

图——广度优先遍历

#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;
}

posted on 2017-05-08 16:43  七昂的技术之旅  阅读(324)  评论(0编辑  收藏  举报

导航