/**
*
* 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;
}
C/C++: 数据结构之图——DFS && BFS
最新推荐文章于 2024-10-08 16:16:22 发布