C++无向图判断是否存在回路。(并查集的思想)

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

 

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值