参考王红梅、胡明、王涛编著的《数据结构(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;
}