본문 바로가기
Algorithm/BFS, DFS

[백준] 10451번 순열 사이클

by 등촌동 꼬북이 2020. 9. 21.

간단한 탐색이기 때문에

 

DFS로 풀면 금방 한다

 

아주 간단한 재귀로 금방 풀 수 있는 문제 

 

import sys
N = int(input())

def DFS(i):
    visited[i] = True
    for ni in graph[i]:
        if visited[ni] is False:
            DFS(ni)

for _ in range(N):
    counter = 0
    M = int(input())
    graph = [[] for _ in range(M + 1)]
    visited = [False] * (M + 1)
    data = list(map(int, sys.stdin.readline().split()))
    for i in range(1, len(data) + 1):
        graph[i].append(data[i - 1])
    for i in range(1, M + 1):
        if visited[i] is False:
            DFS(i)
            counter += 1
    print(counter)

'Algorithm > BFS, DFS' 카테고리의 다른 글

[백준] 7562번 나이트의 이동  (0) 2020.09.23
[백준] 1600번 말이 되고픈 원숭이  (0) 2020.09.23
[백준] 11724번 연결 요소의 개수  (0) 2020.09.20
[백준] 16953번 A → B  (0) 2020.09.20
[백준] 1967번 숨바꼭질  (0) 2020.09.15

댓글