Skip to content

Commit

Permalink
[Add] 사이클 판별 알고리즘 (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
heerucan committed Mar 27, 2022
1 parent a80f4a1 commit 9086500
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions CodingTest/CH10 그래프 이론/사이클판별알고리즘.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]

# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b

# 노드와 간선 개수 입력받기
v, e = map(int, input().split())
parent = [0]*(v+1) #부모 테이블 초기화

# 부모 테이블 상에서, 부모를 자기 자신으로 초기화
for i in range(1, v+1):
parent[i] = i

cycle = False

for i in range(e):
a, b = map(int, input().split())
# 사이클이 발생한 경우 종료
if find_parent(parent, a) == find_parent(parent, b):
cycle = True
break
else:
union_parent(parent, a, b)

if cycle:
print("사이클이 발생했다.")
else:
print("사이클이 발생하지 않았다.")
Empty file.
Empty file.

0 comments on commit 9086500

Please sign in to comment.