Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法

利用Union Find的方法查找图中是否有环。

在于构建一个图数据结构,和一般图的数据结构不同的是这个图是记录了边的图,并在查找过程中不断把边连接起来,形成一个回路。

原文地址:

http://www.geeksforgeeks.org/union-find/

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

class UnionFind
{
	struct Edge
	{
		int src, des;
		explicit Edge(int s = 0, int d = 0) : src(s), des(d) {}
	};

	struct Graph
	{
		int V, E; // V-> Number of vertices, E-> Number of edges
		Edge *edges;
		Graph(int v, int e) : V(v), E(e), edges(new Edge[e])
		{
		}
		~Graph()
		{
			if (edges) delete [] edges;
		}
	};

	int find(int parent[], int i)
	{
		if (-1 == parent[i]) return i;
		return find(parent, parent[i]);
	}

	void unionTwo(int parent[], int x, int y)
	{
		int xset = find(parent, x);
		int yset = find(parent, y);
		parent[xset] = yset;
	}

	bool isCycle(Graph *gra)
	{
		int *parent = (int *) malloc (gra->V * sizeof(int));
		std::fill(parent, parent+gra->V, -1);

		for (int i = 0; i < gra->E; i++)
		{
			int x = find(parent, gra->edges[i].src);
			int y = find(parent, gra->edges[i].des);
			if (x == y) return true;
			unionTwo(parent, x, y);
		}
		return false;
	}
public:
	UnionFind()
	{
		Graph *gra = new Graph(3, 3);

		gra->edges[0].src = 0;
		gra->edges[0].des = 1;

		gra->edges[1].src = 1;
		gra->edges[1].des = 2;

		gra->edges[2].src = 0;
		gra->edges[2].des = 2;

		if (isCycle(gra))
			printf( "Graph contains cycle\n" );
		else
			printf( "Graph doesn't contain cycle\n" );

		delete gra;
	}
};





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值