检查给定图是否包含循环。
例子:
输入: 输出:图形包含循环。输入: 输出:图形不包含循环。
先决条件:不交集(或并集查找),按等级和路径压缩的并集
我们已经讨论了联合发现以检测周期。在这里,我们讨论通过路径压缩查找,在这种情况下,它经过稍微修改以比原始方法更快地工作,因为每次上图时我们都跳过一个级别。查找函数的实现是迭代的,因此不涉及开销。优化查找函数复杂度为O(log *(n)),即迭代对数,对于重复调用,该对数收敛到O(1)。
请参阅此链接以获取
联合证明的对数*(n)复杂度证明
查找函数的说明:
以示例1理解find函数:
(1)首次调用find(8),映射将如下所示:
查找函数花了3个映射来获取节点8的根。映射如下所示:
从节点8跳过节点7,到达节点6。
从节点6跳过节点5,到达节点4。
从节点4跳过节点2,到达节点0。
(2)再次调用find(8),映射将如下所示:
查找函数花了2个映射来获取节点8的根。映射如下所示:
从节点8,跳过节点5,节点6和节点7,到达节点4。
从节点4跳过节点2,到达节点0。
(3)第三次调用find(8),映射将如下所示:
最后,我们发现find函数仅用1个映射即可获取节点8的根。映射如下所示:
从节点8跳过节点5,节点6,节点7,节点4和节点2,到达节点0。
这就是它将收敛从某些映射到单个映射的路径的方式。
示例1的说明
最初,数组大小和Arr看起来像:
Arr [9] = {0、1、2、3、4、5、6、7、8}
大小[9] = {1,1,1,1,1,1,1,1,1}
考虑图中的边,并如下所示将它们一个一个地添加到不相交的联合集中:
优势1:0-1
find(0)=> 0,find(1)=> 1,两者都有不同的根父级
将它们放在单个连接的组件中,因为当前它们不属于不同的连接组件。
Arr [1] = 0,大小[0] = 2;
边缘2:0-2
find(0)=> 0,find(2)=> 2,两者都有不同的根父级
Arr [2] = 0,大小[0] = 3;
优势3:1-3
find(1)=> 0,find(3)=> 3,两者都有不同的根父级
Arr [3] = 0,大小[0] = 3;
优势4:3-4
find(3)=> 1,find(4)=> 4,两者都有不同的根父级
Arr [4] = 0,大小[0] = 4;
优势5:2-4
find(2)=> 0,find(4)=> 0,两者都有相同的根父级
因此,图中存在一个循环。
我们停止进一步检查图中的周期。
C++
// CPP program to implement Union-Find with union
// by rank and path compression.
#include
using namespace std;
const int MAX_VERTEX = 101;
// Arr to represent parent of index i
int Arr[MAX_VERTEX];
// Size to represent the number of nodes
// in subgxrph rooted at index i
int size[MAX_VERTEX];
// set parent of every node to itself and
// size of node to one
void initialize(int n)
{
for (int i = 0; i <= n; i++) {
Arr[i] = i;
size[i] = 1;
}
}
// Each time we follow a path, find function
// compresses it further until the path length
// is greater than or equal to 1.
int find(int i)
{
// while we reach a node whose parent is
// equal to itself
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]]; // Skip one level
i = Arr[i]; // Move to the new level
}
return i;
}
// A function that does union of two nodes x and y
// where xr is root node of x and yr is root node of y
void _union(int xr, int yr)
{
if (size[xr] < size[yr]) // Make yr parent of xr
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else // Make xr parent of yr
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
// The main function to check whether a given
// gxrph contains cycle or not
int isCycle(vector adj[], int V)
{
// Itexrte through all edges of gxrph, find
// nodes connecting them.
// If root nodes of both are same, then there is
// cycle in gxrph.
for (int i = 0; i < V; i++) {
for (int j = 0; j < adj[i].size(); j++) {
int x = find(i); // find root of i
int y = find(adj[i][j]); // find root of adj[i][j]
if (x == y)
return 1; // If same parent
_union(x, y); // Make them connect
}
}
return 0;
}
// Driver progxrm to test above functions
int main()
{
int V = 3;
// Initialize the values for arxry Arr and Size
initialize(V);
/* Let us create following gxrph
0
| \
| \
1-----2 */
vector adj[V]; // Adjacency list for gxrph
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(2);
// call is_cycle to check if it contains cycle
if (isCycle(adj, V))
cout << "Gxrph contains Cycle.\n";
else
cout << "Gxrph does not contain Cycle.\n";
return 0;
}
Java
// Java program to implement Union-Find with union
// by rank and path compression
import java.util.*;
class GFG
{
static int MAX_VERTEX = 101;
// Arr to represent parent of index i
static int []Arr = new int[MAX_VERTEX];
// Size to represent the number of nodes
// in subgxrph rooted at index i
static int []size = new int[MAX_VERTEX];
// set parent of every node to itself and
// size of node to one
static void initialize(int n)
{
for (int i = 0; i <= n; i++)
{
Arr[i] = i;
size[i] = 1;
}
}
// Each time we follow a path, find function
// compresses it further until the path length
// is greater than or equal to 1.
static int find(int i)
{
// while we reach a node whose parent is
// equal to itself
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]]; // Skip one level
i = Arr[i]; // Move to the new level
}
return i;
}
// A function that does union of two nodes x and y
// where xr is root node of x and yr is root node of y
static void _union(int xr, int yr)
{
if (size[xr] < size[yr]) // Make yr parent of xr
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else // Make xr parent of yr
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
// The main function to check whether a given
// gxrph contains cycle or not
static int isCycle(Vector adj[], int V)
{
// Itexrte through all edges of gxrph,
// find nodes connecting them.
// If root nodes of both are same,
// then there is cycle in gxrph.
for (int i = 0; i < V; i++)
{
for (int j = 0; j < adj[i].size(); j++)
{
int x = find(i); // find root of i
// find root of adj[i][j]
int y = find(adj[i].get(j));
if (x == y)
return 1; // If same parent
_union(x, y); // Make them connect
}
}
return 0;
}
// Driver Code
public static void main(String[] args)
{
int V = 3;
// Initialize the values for arxry Arr and Size
initialize(V);
/* Let us create following gxrph
0
| \
| \
1-----2 */
// Adjacency list for graph
Vector []adj = new Vector[V];
for(int i = 0; i < V; i++)
adj[i] = new Vector();
adj[0].add(1);
adj[0].add(2);
adj[1].add(2);
// call is_cycle to check if it contains cycle
if (isCycle(adj, V) == 1)
System.out.print("Graph contains Cycle.\n");
else
System.out.print("Graph does not contain Cycle.\n");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to implement Union-Find
# with union by rank and path compression.
# set parent of every node to itself
# and size of node to one
def initialize(n):
global Arr, size
for i in range(n + 1):
Arr[i] = i
size[i] = 1
# Each time we follow a path, find
# function compresses it further
# until the path length is greater
# than or equal to 1.
def find(i):
global Arr, size
# while we reach a node whose
# parent is equal to itself
while (Arr[i] != i):
Arr[i] = Arr[Arr[i]] # Skip one level
i = Arr[i] # Move to the new level
return i
# A function that does union of two
# nodes x and y where xr is root node
# of x and yr is root node of y
def _union(xr, yr):
global Arr, size
if (size[xr] < size[yr]): # Make yr parent of xr
Arr[xr] = Arr[yr]
size[yr] += size[xr]
else: # Make xr parent of yr
Arr[yr] = Arr[xr]
size[xr] += size[yr]
# The main function to check whether
# a given graph contains cycle or not
def isCycle(adj, V):
global Arr, size
# Itexrte through all edges of gxrph,
# find nodes connecting them.
# If root nodes of both are same,
# then there is cycle in gxrph.
for i in range(V):
for j in range(len(adj[i])):
x = find(i) # find root of i
y = find(adj[i][j]) # find root of adj[i][j]
if (x == y):
return 1 # If same parent
_union(x, y) # Make them connect
return 0
# Driver Code
MAX_VERTEX = 101
# Arr to represent parent of index i
Arr = [None] * MAX_VERTEX
# Size to represent the number of nodes
# in subgxrph rooted at index i
size = [None] * MAX_VERTEX
V = 3
# Initialize the values for arxry
# Arr and Size
initialize(V)
# Let us create following gxrph
# 0
# | \
# | \
# 1-----2
# Adjacency list for graph
adj = [[] for i in range(V)]
adj[0].append(1)
adj[0].append(2)
adj[1].append(2)
# call is_cycle to check if it
# contains cycle
if (isCycle(adj, V)):
print("Graph contains Cycle.")
else:
print("Graph does not contain Cycle.")
# This code is contributed by PranchalK
C#
// C# program to implement Union-Find
// with union by rank and path compression
using System;
using System.Collections.Generic;
class GFG
{
static int MAX_VERTEX = 101;
// Arr to represent parent of index i
static int []Arr = new int[MAX_VERTEX];
// Size to represent the number of nodes
// in subgxrph rooted at index i
static int []size = new int[MAX_VERTEX];
// set parent of every node to itself
// and size of node to one
static void initialize(int n)
{
for (int i = 0; i <= n; i++)
{
Arr[i] = i;
size[i] = 1;
}
}
// Each time we follow a path,
// find function compresses it further
// until the path length is greater than
// or equal to 1.
static int find(int i)
{
// while we reach a node whose
// parent is equal to itself
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]]; // Skip one level
i = Arr[i]; // Move to the new level
}
return i;
}
// A function that does union of
// two nodes x and y where xr is
// root node of x and yr is root node of y
static void _union(int xr, int yr)
{
if (size[xr] < size[yr]) // Make yr parent of xr
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else // Make xr parent of yr
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
// The main function to check whether
// a given graph contains cycle or not
static int isCycle(List []adj, int V)
{
// Itexrte through all edges of graph,
// find nodes connecting them.
// If root nodes of both are same,
// then there is cycle in graph.
for (int i = 0; i < V; i++)
{
for (int j = 0; j < adj[i].Count; j++)
{
int x = find(i); // find root of i
// find root of adj[i][j]
int y = find(adj[i][j]);
if (x == y)
return 1; // If same parent
_union(x, y); // Make them connect
}
}
return 0;
}
// Driver Code
public static void Main(String[] args)
{
int V = 3;
// Initialize the values for
// array Arr and Size
initialize(V);
/* Let us create following graph
0
| \
| \
1-----2 */
// Adjacency list for graph
List []adj = new List[V];
for(int i = 0; i < V; i++)
adj[i] = new List();
adj[0].Add(1);
adj[0].Add(2);
adj[1].Add(2);
// call is_cycle to check if it contains cycle
if (isCycle(adj, V) == 1)
Console.Write("Graph contains Cycle.\n");
else
Console.Write("Graph does not contain Cycle.\n");
}
}
// This code is contributed by Rajput-Ji
输出:
Graph contains Cycle.
时间复杂度(查找): O(log *(n))
时间复杂度(联盟): O(1)