首页 > 其他 > 详细

Graph-BFS-图的广度优先遍历

时间:2017-02-11 12:44:39      阅读:210      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <queue>

using namespace std;

/*
5 5
1 2
1 3
1 5
2 4
3 5
1 2 3 5 4
--------------------------------
Process exited with return value 0
Press any key to continue . . .
*/

int sum = 1;
int vertx, edge;
int Graph[20][20] = {0}, book[20] = {0};

void BFS()
{	
	//队列 
	queue<int> qgraph;

	//标记第一个元素已经访问,并压入队列中。 
	book[1] = 1;
	qgraph.push(1);
	
	//当队列不为空时 
	while(!qgraph.empty())
	{
		int x = qgraph.front();
		for(int i = 1; i <= vertx; i++)
		{
			if(Graph[x][i] == 1 && book[i] == 0)
			{
				sum++; 
				book[i] = 1;
				qgraph.push(i);
			}
		}
		
		cout << qgraph.front() << " ";
		qgraph.pop();
	}
	
	return;
}

int main()
{
	cin >> vertx >> edge;
	
	for(int i = 1; i <= vertx; i++)
	{
		for(int j = 1; j <= vertx; j++)
		{
			if(i == j) Graph[i][j] = 0;
			Graph[i][j] = 999999;
		}
	}
	
	for(int i = 1; i <= edge; i++)
	{
		int x, y;
		cin >> x >> y;
		Graph[x][y] = 1;
		Graph[y][x] = 1;
	}
	
	BFS();
	
	return 0;
} 

  

Graph-BFS-图的广度优先遍历

原文:http://www.cnblogs.com/hfultrastrong/p/6388844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!