Union-Find 检测无向图有无环路算法
不相交集合数据结构(Disjoint-set data structure)是一种用于跟踪集合被分割成多个不相交的子集合的数据结构,每个集合通过一个代表来标识,代表即集合中的某个成员。
Union-Find 算法为该数据结构提供了两种非常有用的操作:
- Find:判断子集中是否存在特定的元素。可以用于检测是否两个元素存在于相同的子集中。
- Union:将两个不子集合并成新的子集合。
Union-Find 算法的一个具体的应用就是在无向图(Undirected Graph)中检测是否存在环路(Cycle)。
例如,下面这张无向图 G:
0
| \
| \
1-----2
G 中包含 3 个顶点和 3 条边 {{0, 1}, {1, 2}, {2, 1}}。
初始时,设 int[] parent = new int[VertexCount],默认每个顶点的子集中只有自己,设为 -1。
0 1 2
-1 -1 -1
处理边 {0, 1},Find 顶点 0 和 1 的子集,发现它们在不同的子集中,则 Union 它们,此时 1 代表了子集 {0, 1}。
0 1 2
1 -1 -1
处理边 {1, 2},Find 顶点 1 和 2 的子集,发现它们在不同的子集中,则 Union 它们,此时 2 代表了子集 {0, 1, 2}。
0 1 2
1 2 -1
处理边 {2, 1},Find 顶点 2 和 1 的子集,发现它们在相同的子集中,则图存在环。
Union-Find 算法简单实现如下,其时间复杂度为 O(n)。
using System;
using System.Collections.Generic;
using System.Linq; namespace GraphAlgorithmTesting
{
class Program
{
static void Main(string[] args)
{
Graph g = new Graph();
g.AddEdge(, , );
g.AddEdge(, , );
g.AddEdge(, , );
g.AddEdge(, , );
//g.AddEdge(2, 1, 4);
g.AddEdge(, , );
//g.AddEdge(3, 2, 9);
g.AddEdge(, , );
//g.AddEdge(4, 3, 7);
//g.AddEdge(4, 5, 4); Console.WriteLine();
Console.WriteLine("Graph Vertex Count : {0}", g.VertexCount);
Console.WriteLine("Graph Edge Count : {0}", g.EdgeCount);
Console.WriteLine(); Console.WriteLine("Is there cycle in graph: {0}", g.HasCycle()); Console.ReadKey();
} class Edge
{
public Edge(int begin, int end, int weight)
{
this.Begin = begin;
this.End = end;
this.Weight = weight;
} public int Begin { get; private set; }
public int End { get; private set; }
public int Weight { get; private set; } public override string ToString()
{
return string.Format(
"Begin[{0}], End[{1}], Weight[{2}]",
Begin, End, Weight);
}
} class Graph
{
private Dictionary<int, List<Edge>> _adjacentEdges
= new Dictionary<int, List<Edge>>(); public Graph(int vertexCount)
{
this.VertexCount = vertexCount;
} public int VertexCount { get; private set; } public IEnumerable<int> Vertices { get { return _adjacentEdges.Keys; } } public IEnumerable<Edge> Edges
{
get { return _adjacentEdges.Values.SelectMany(e => e); }
} public int EdgeCount { get { return this.Edges.Count(); } } public void AddEdge(int begin, int end, int weight)
{
if (!_adjacentEdges.ContainsKey(begin))
{
var edges = new List<Edge>();
_adjacentEdges.Add(begin, edges);
} _adjacentEdges[begin].Add(new Edge(begin, end, weight));
} private int Find(int[] parent, int i)
{
if (parent[i] == -)
return i;
return Find(parent, parent[i]);
} private void Union(int[] parent, int x, int y)
{
int xset = Find(parent, x);
int yset = Find(parent, y);
parent[xset] = yset;
} public bool HasCycle()
{
int[] parent = new int[VertexCount];
for (int i = ; i < parent.Length; i++)
{
parent[i] = -;
} // Iterate through all edges of graph, find subset of both
// vertices of every edge, if both subsets are same,
// then there is cycle in graph.
foreach (var edge in this.Edges)
{
int x = Find(parent, edge.Begin);
int y = Find(parent, edge.End); if (x == y)
{
return true;
} Union(parent, x, y);
} return false;
}
}
}
}
本篇文章《Union-Find 检测无向图有无环路算法》由 Dennis Gao 发表自博客园,未经作者本人同意禁止任何形式的转载,任何自动或人为的爬虫转载行为均为耍流氓。
Union-Find 检测无向图有无环路算法的更多相关文章
- CVPR目标检测与实例分割算法解析:FCOS(2019),Mask R-CNN(2019),PolarMask(2020)
CVPR目标检测与实例分割算法解析:FCOS(2019),Mask R-CNN(2019),PolarMask(2020)1. 目标检测:FCOS(CVPR 2019)目标检测算法FCOS(FCOS: ...
- [算法]检测空间三角形相交算法(Devillers & Guigue算法)
#pragma once //GYDevillersTriangle.h /* 快速检测空间三角形相交算法的代码实现(Devillers & Guigue算法) 博客原地址:http://bl ...
- UEBA 学术界研究现状——用户行为异常检测思路:序列挖掘prefixspan,HMM,LSTM/CNN,SVM异常检测,聚类CURE算法
论文 技术分析<关于网络分层信息泄漏点快速检测仿真> "1.基于动态阈值的泄露点快速检测方法,采样Mallat算法对网络分层信息的离散采样数据进行离散小波变换;利用滑动窗口对该尺 ...
- 特征点检测学习_2(surf算法)
依旧转载自作者:tornadomeet 出处:http://www.cnblogs.com/tornadomeet 特征点检测学习_2(surf算法) 在上篇博客特征点检测学习_1(sift算法) 中 ...
- 模式匹配之surf----特征点检测学习_2(surf算法)
在上篇博客特征点检测学习_1(sift算法) 中简单介绍了经典的sift算法,sift算法比较稳定,检测到的特征点也比较多,其最大的确定是计算复杂度较高.后面有不少学者对其进行了改进,其中比较出名的就 ...
- 图论 Make Unique:有向图和无向图的一些算法
计算机科学入门资料之一的<算法与数据结构-C语言版>,覆盖了基础算法的几乎所有分支,其中的一个典型分支为图理论. 一个简介:图论基础-图数据结构基础 一个简洁的博客:图论基础,简列一本书 ...
- 当我们谈论算法我们在谈论什么:由疫情核酸检测想到的分治算法(Divide-and-Conquer)
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_159 北京的疫情一波未平一波又起,由此看来,战"疫"将是一场旷日持久的战争,绝不能掉以轻心.轻易言胜.病毒随时 ...
- 无向图的最短路径算法JAVA实现
一,问题描述 给出一个无向图,指定无向图中某个顶点作为源点.求出图中所有顶点到源点的最短路径. 无向图的最短路径其实是源点到该顶点的最少边的数目. 本文假设图的信息保存在文件中,通过读取文件来构造图. ...
- 无向图的最短路径算法JAVA实现(转)
一,问题描述 给出一个无向图,指定无向图中某个顶点作为源点.求出图中所有顶点到源点的最短路径. 无向图的最短路径其实是源点到该顶点的最少边的数目. 本文假设图的信息保存在文件中,通过读取文件来构造图. ...
随机推荐
- 前端试题本(Javascript篇)
JS1. 下面这个JS程序的输出是什么:JS2.下面的JS程序输出是什么:JS3.页面有一个按钮button id为 button1,通过原生的js如何禁用?JS4.页面有一个按钮button id为 ...
- Javascript-常用字符串数组操作
字符串的操作在编写Js的过程中是不可避免的 因为它太多的API 还有相似的API让我们很头痛 为了避免以后遇到模拟两可的问题 还是做个笔记比较好 把常用的字符串操作记录下来成笔记 方便以后查找 No1 ...
- python爬虫实战
http://www.jb51.net/article/57161.htm python在线编程:http://www.pythontip.com/coding/run c语言在线编程:http:// ...
- 关于linux服务器上搭建ftp服务的流程
小龙最近折腾了一个阿里云的服务器,买完了就要开始做那么多那么多的功课,小龙对ssh也是一知半解的状态,做个小笔记,发布下整个ftp服务的搭建过程,大神勿喷:) 一.aliyun Linux(Redha ...
- Greenplum安装
最近需要安装Greenplum测试一些东西,在安装过程中出现了许多问题,所以在这里将安装过程整理一下,主要参考<Greenplum企业应用实践>和http://jxzhfei.blog.5 ...
- iPhone/iPad/Android UI尺寸规范 UI尺寸规范,UI图标尺寸,UI界面尺寸,iPhone6尺寸,iPhone6 Plus尺寸,安卓尺寸,iOS尺寸
iPhone/iPad/Android UI尺寸规范 UI尺寸规范,UI图标尺寸,UI界面尺寸,iPhone6尺寸,iPhone6 Plus尺寸,安卓尺寸,iOS尺寸 iPhone界面尺寸 设备 分辨 ...
- JS 中 Array.slice() 和 Array.splice()方法
slice slice()就是对应String的substring()版本,它截取Array的部分元素,然后返回一个新的Array: var arr = ['A', 'B', 'C', 'D', 'E ...
- NOIP2016普及
还记得去年局部变量忘记置零coin爆零的事......结果我今年又要考一年普及[趴 最近沉迷分块莫队无法自拔,这几天才想起来我是个普及组选手 几乎没准备普及,周六上午抱抱佛脚好了...... 希望能顺 ...
- echo.js 延迟加载图片控件
echo.js的github地址:https://github.com/toddmotto/echo echo是一个独立的JavaScript.轻量级的.延迟图片加载插件,echo压缩后体积不到1 ...
- 2632: [neerc2011]Gcd guessing game
2632: [neerc2011]Gcd guessing game Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 144 Solved: 84[S ...