![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e3d61b43af88abd2e9cdac1cc64cbc2.jpeg)
def find_root(x, parent):
x_root = x
while parent[x_root] != -1:
x_root = parent[x_root]
return x_root
def union_vertices(x, y, parent):
x_root = find_root(x, parent)
y_root = find_root(y, parent)
if x_root == y_root:
return 0
else:
parent[x_root] = y_root
return 1
n = int(input())
arr = []
for i in range(n):
ss = list(map(int, input().split(' ')))
arr.append(ss)
edges = []
for i in range(n):
for j in range(n):
if arr[i][j] == 1:
edge = [i, j]
edges.append(edge)
print(edges)
parent = [-1] * n
find = False
for i in range(0, len(edges)):
x = edges[i][0]
y = edges[i][1]
if union_vertices(x, y, parent) == 0:
find = True
break
if find == True:
print("Cycle detected!\n")
else:
print("No cycles found.")
'''
3
0 0 1
1 0 0
0 1 0
[[0, 2], [1, 0], [2, 1]]
Cycle detected!
'''
#include <stdio.h>
#include <cstdlib>
#define VERTICES 6
void initialise(int parent[]){
int i;
for(i=0; i<VERTICES; i++){
parent[i] = -1;
}
}
int find_root(int x, int parent[]){
int x_root = x;
while (parent[x_root] != -1){
x_root = parent[x_root];
}
return x_root;
}
int union_vertices(int x, int y, int parent[]){
int x_root = find_root(x, parent);
int y_root = find_root(y, parent);
if(x_root == y_root){
return 0;
}
else{
parent[x_root] = y_root;
return 1;
}
}
int main(void) {
int parent[VERTICES] = {0};
int edges[6][5] = {
{0,1},{1,2},{1,3},
{2,4},{3,4},{2,5}
};
initialise(parent);
int i;
for (i=0;i<6;i++){
int x = edges[i][0];
int y = edges[i][1];
if(union_vertices(x,y,parent)==0){
printf("Cycle detected!\n");
exit(0);
}
}
printf("No cycles found.\n");
return 0;
}