参考王红梅、胡明、王涛编著的《数据结构(C++版)》中的思想,采用并查集判断无向图是否存在回路。
//无向图判断是否有环路。
#include <iostream>
using namespace std;
#define N 1000
typedef struct edge
{
int from;
int to;
int weight;
};
edge A[N];
int n, m;
int parent[N];
int Findroot(int a);
int main()
{
int vex1, vex2;
int cnt = 0;
cout << "Please enter the number of vertex in your graph:" << endl;
cin >> n;
for (int i = 1; i <= n; i++)
parent[i] = -1;
cout << "Please enter the number of edge in your graph:" << endl;
cin >> m;
cout << "Please enter the edge in your graph:" << endl;
for (int i = 1; i <= m; i++)
{
cin >> A[i].from >> A[i].to >> A[i].weight;
}
for (int i = 1; i <= m; i++)
{
vex1 = Findroot(A[i].from);
vex2 = Findroot(A[i].to);
if (vex1 == vex2)
{
cout << "图中有环!" << endl;
cnt = 1;
break;
}
else
{
parent[vex1] = vex2;
}
}
if (cnt == 0)
{
cout << "图为无环图1" << endl;
}
system("pause");
return 0;
}
int Findroot(int a)
{
int t = a;
while (parent[t] != -1)
t = parent[t];
return t;
}
无向图环路检测
本文介绍了一种使用并查集算法判断无向图中是否存在环路的方法,通过《数据结构(C++版)》一书的思想,实现了一个C++程序来演示这一过程。程序首先读取图的顶点数和边数,然后输入各边的连接情况,最后利用并查集的查找和合并操作判断图中是否存在环路。
2477

被折叠的 条评论
为什么被折叠?



