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

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

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/wsqiangz/article/details/71424932
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞