BFS遍历连通图

//广度优先搜索遍历连通图
#include<iostream>
using namespace std;
#define MVNum 100
#define MAXQSIZE 100
typedef char VerTexType;
typedef int ArcType;
bool visited[MVNum];
typedef struct {
	VerTexType vexs[MVNum];
	ArcType arcs[MVNum][MVNum];
	int vexnum, arcnum;
}Graph;
typedef struct {
	ArcType* base;
	int front;
	int rear;
}sqQueue;
void InitQueue(sqQueue& Q)
{
	Q.base = new ArcType[MAXQSIZE];
	if (!Q.base)
	{
		exit(0);
	}
	Q.front = Q.rear = 0;
}
void EnQueue(sqQueue& Q, ArcType e)
{
	if ((Q.rear + 1) % MAXQSIZE == Q.front)
	{
		return;
	}
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXQSIZE;
}
bool QueueEmpty(sqQueue Q)
{
	if (Q.rear == Q.front)
	{
		return true;
	}
	return false;
}
void DeQueue(sqQueue& Q, ArcType& u)
{
	u = Q.base[Q.front];
	Q.front = (Q.front + 1) % MAXQSIZE;
}
int LocateVex(Graph G, VerTexType v)
{
	for (int i = 0; i < G.vexnum; i++)
	{
		if (G.vexs[i] == v)
		{
			return i;
		}
	}
	return -1;
}
void CreateUDN(Graph &G)
{
	cout << "请输入总顶点数,总边数:";
	cin >> G.vexnum >> G.arcnum;
	cout << endl;
	cout << "请输入点的名称" << endl;
	for (int i = 0; i < G.vexnum; i++)
	{
		cout << "请输入第" << i + 1 << "个点的名称:";
		cin >> G.vexs[i];
	}
	for (int i = 0; i < G.vexnum; i++)
	{
		for (int j = 0; j < G.vexnum; j++)
		{
			G.arcs[i][j] = 0;
		}
	}
	cout << endl;
	cout << "请输入边依附的顶点" << endl;
	for (int k = 0; k < G.arcnum; k++)
	{
		VerTexType v1, v2;
		cout << "请输入第" << k + 1 << "条边依附的顶点:";
		cin >> v1 >> v2;
		int i = LocateVex(G, v1);
		int j = LocateVex(G, v2);
		G.arcs[i][j] = G.arcs[j][i] = 1;
	}
}
int FirstAdjVex(Graph G, int v)
{
	for (int i = 0; i < G.vexnum; i++)
	{
		if (G.arcs[v][i] == 1 && visited[i] == false)
		{
			return i;
		}
	}
	return -1;
}
int NextAdjVex(Graph G, int u, int w)
{
	for (int i = w; i < G.vexnum; i++)
	{
		if (G.arcs[u][i] == 1 && visited[i] == false)
		{
			return i;
		}
	}
	return -1;
}
void BFS(Graph G, int v)
{
	sqQueue Q;
	ArcType u, w;
	cout << G.vexs[v] << " ";
	visited[v] = true;
	InitQueue(Q);
	EnQueue(Q, v);
	while (!QueueEmpty(Q))
	{
		DeQueue(Q, u);
		for (w = FirstAdjVex(G, u); w >= 0; w = NextAdjVex(G, u, w))
		{
			if (!visited[w])
			{
				cout << G.vexs[w] << " ";
			    visited[w] = true;
				EnQueue(Q, w);
			}
		}
	}
}
int main()
{
	cout << "BFS遍历连通图" << endl;
	Graph G;
	CreateUDN(G);
	cout << endl;
	cout << "请输入遍历连通图的起始点:";
	VerTexType c;
	cin >> c;
	int i;
	for (i = 0; i < G.vexnum; i++)
	{
		if (c == G.vexs[i])
		{
			break;
		}
	}
	while (i >= G.vexnum)
	{
		cout << "该点不存在,请重新输入! " << endl;
		cout << "请输入遍历连通图的起始点:";
		cin >> c;
		for (i = 0; i < G.vexnum; i++)
		{
			if (c == G.vexs[i])
			{
				break;
			}
		}
	}
	cout << "广度优先搜索遍历连通图结果:" << endl;
	BFS(G, i);
	return 0;
}

BFS遍历连通图

BFS遍历连通图

上一篇:本周总结2021-11-13


下一篇:黑马期中考试(字符串替换)