Graph-BFS-Fly-图的广度优先遍历-最小转机问题

Posted Archibald Witwicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Graph-BFS-Fly-图的广度优先遍历-最小转机问题相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <queue>

using namespace std;

/*
5 7 1 5
1 2
1 3
2 3
2 4
3 4
3 5
4 5

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

class Node
{
public:
	Node(int _x, int _z);
	
public:
	int x;
	int z;
};

Node::Node(int _x, int _z)
{
	this->x = _x;
	this->z = _z; 
}

const int infinity = 999999;
int vertx, edge, start, end;
int Graph[20][20] = {0}, book[20] = {0};
queue<Node> qgraph;

void BFS()
{
	book[start] = 1;
	Node firstnode(start, 0);
	qgraph.push(firstnode);
	
	while(!qgraph.empty())
	{
		int flag = 0;
		
		int x = qgraph.front().x;
		
		for(int i = 1; i <= vertx; i++)
		{
			if(Graph[x][i] != infinity && book[i] == 0)
			{
				book[i] = 1;
				
				Node node(i, qgraph.front().z + 1); 
				
				qgraph.push(node);
			}
			
			if(qgraph.back().x == end)
			{
				flag = 1;
				break;	
			}
		}
		
		if(flag == 1)
		{
			break;
		}
		
		qgraph.pop();
	}
	
	return;
}

int main()
{
	cin >> vertx >> edge >> start >> end;
	for(int i = 1; i <= vertx; i++)
	{
		for(int j = 1; j <= vertx; j++)
		{
			if(i == j)
			{
				Graph[i][j] = 0;
			}
			Graph[i][j] = infinity;
		}
	} 
	
	for(int j = 1; j <= edge; j++)
	{
		int x, y;
		cin >> x >> y;
		Graph[x][y] = 1;
		Graph[y][x] = 1;
	}
	
	BFS();
	
	cout << endl << qgraph.back().z;
		
	return 0; 
} 

  

以上是关于Graph-BFS-Fly-图的广度优先遍历-最小转机问题的主要内容,如果未能解决你的问题,请参考以下文章

图的深度/广度优先遍历C语言程序

c语言图的遍历,邻接表存储,深度,广度优先遍历

什么是图的深度优先遍历?什么是图的广度优先遍历?

算法专题 之 广度优先搜索

图的广度遍历和深度遍历

图的遍历:深度优先遍历,广度优先遍历