算法和数据结构项目练习7-广度优先搜索(BFS)

Breadth First Search

项目介绍

  1. 本项目实现广度优先搜索算法。
  2. 读取txt文件中第一行表示图中顶点数的单个整数N
  3. 读取txt文件中第二行开始是一对对的整数。每一对表示图中某条边两端的两个顶点。
  4. 图是无向的,因此节点编号为0 - N‐1。
  5. 程序先遍历图的顶点,从节点0开始,输出从这个节点可以到达的所有节点。
  6. 输出包含从算法获得的生成树。它应该被打印成树中有序的边列表。每条边的顶点应该按照BFS遍历的顺序列出。

输入的txt文件如下:
在这里插入图片描述
其中第一行是总的顶点数,后面的两列组成的对表示一条边上的两个顶点。

代码实现

#include <iostream>
#include <fstream>

using namespace std;

//Two lines' array with maximum 200 rows
int VerticesEdge[200][200];
int Vertices[200];
int queue[200];
int QueueNumber = 0;
int Index = 0;// Vertices index


void AddVertices(int i);
void Inqueue(int i);
void Dequeue();
bool Check(int x);//check repeat

int main()
{
	int EdgeNumbers = 0;//used for edge counting
	int TotalVertices;//read the number of vertex
	int LeftVertices;//	Left column vertex 
	int RightVertices;//Right column vertex 
	ifstream read;
	string a;
	cout << "Please enter the filename: " << endl;
	cin >>a;
	read.open(a.c_str());
	if (!read)
	{
		cout << "Can not find the file" << endl;
		exit(1);
	}
	read >> TotalVertices;
	while (!read.eof())
	{
		read >> LeftVertices;
		read >> RightVertices;
		VerticesEdge[LeftVertices][RightVertices] = 1;
		VerticesEdge[RightVertices][LeftVertices] = 1;
		EdgeNumbers++;
	}

	read.close();
	EdgeNumbers--;//There is a space line at the end of the file

	Inqueue( VerticesEdge[0][0]);//write root node into queue
	AddVertices( VerticesEdge[0][0]);
	while ( QueueNumber != 0)
	{
		for (int x = 0; x < TotalVertices; x++)
		{


			if ( VerticesEdge[queue[0]][x] == 1)
			{


				if (Check(x) ==false)
				{
					AddVertices(x);

					Inqueue(x);

					cout << queue[0] << "  " << x << endl;
				}

			}

		}
		Dequeue();
	}
	return 0;
}

void AddVertices(int a)
{
	Vertices[Index] = a;
	Index++;
}

void Inqueue(int a)
{
	queue[QueueNumber] = a;
	QueueNumber++;
}

void Dequeue()
{
	for (int i = 0; i < QueueNumber; i++)
	{
		queue[i] = queue[i + 1];
	}
	QueueNumber--;
}

bool Check(int x)
{
	int a = 0;
	while (a < Index)
	{
		if (x == Vertices[a])
		{
			return true;
		}
		if (a == Index - 1)
		{
			return false;
		}
		a++;
	}
	
}

输出结果如下所示:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值