C/C++: 数据结构之图——DFS && BFS

/**
*
* Althor: Hacker Hao
* Create: 2023.11.29
*
*/
#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 100
typedef char VerTexType; 
typedef int ArcType;
bool visited[15];

typedef struct 
{
	VerTexType vexs[MAXSIZE]; //顶点表
	ArcType arcs[MAXSIZE][MAXSIZE]; //邻接矩阵
	int vexnum, arcnum; //图的点数、边数
}AMGraph;

//查找顶点
int LocateVex(AMGraph G, int u) 
{
	int i;
	for (i = 1; i <= G.vexnum; i++)
		if (u == G.vexs[i])
			return i;
	return -1;
}

//邻接矩阵
bool CreateUDN(AMGraph& G)
{
	char v1, v2;
	int w, i, j, k;
	cout << "分别输入总顶点数、总边数:" << endl;
	cin >> G.vexnum >> G.arcnum;
	cout << "输入点的信息:" << endl;
	for (i = 1; i <= G.vexnum; i++) 
		cin >> G.vexs[i];
	for (i = 1; i <= G.vexnum; i++)
		for (j = 1; j <= G.vexnum; j++)
			G.arcs[i][j] = 0;
	cout << "请输入一条边所依附的两个顶点、权值:" << endl;
	for (k = 1; k <= G.arcnum; k++) {
		cin >> v1 >> v2 >> w;

		int i = LocateVex(G, v1);
		int j = LocateVex(G, v2);//v1和v2下标

		G.arcs[i][j] = w;
		G.arcs[j][i] = G.arcs[i][j];  //矩阵转置着赋值
	}
	return true;
}

void DFS(AMGraph G, int v)
{
	cout << v << " ";
	visited[v] = true;
	for (int w = 1; w <= G.vexnum; w++)
		if ((G.arcs[v][w] != 0) && (!visited[w]))
			DFS(G, w);
	//邻接点w若未访问,递归DFS 
}
void BFS(AMGraph G, int v)
{
	for (int i = 1; i <= G.vexnum; i++)
		visited[i] = false;

	cout << v << " ";

	visited[v] = true;

	queue<int> Q;  //引入队列,方便层遍
	Q.push(v);
	while (!Q.empty())
	{
		int t = Q.front();
		Q.pop();
		for (int w = 1; w <= G.vexnum; w++)
		{
			if (G.arcs[t][w] == 1 && visited[w] == false)
			{
				visited[w] = true;
				cout << w << " ";
				Q.push(w);
			}
		}
	}
}

int main()
{
	AMGraph G;
	CreateUDN(G);
	cout << "邻接矩阵为:" << endl;
	for (int i = 1; i <= G.vexnum; i++)
	{

		for (int j = 1; j <= G.vexnum; j++) {
			cout << G.arcs[i][j] << " ";
		}
		cout << endl;
	}
	cout << "DFS遍历邻接矩阵结果为:" << endl;
	DFS(G, 2);     //DFS算法的起始位置设置为顶点v2
	cout << endl;

	cout << "BFS遍历邻接矩阵结果为: " << endl;
	BFS(G, 1);     //BFS算法的起始位置设置为v1
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值