https://www.acmicpc.net/problem/10451
import sys
sys.setrecursionlimit(10**6)
def dfs(graph, visited, v):
visited[v] = 1
for i in graph[v]:
if not visited[i]:
dfs(graph, visited, i)
tc = int(sys.stdin.readline())
for _ in range(tc):
num = int(sys.stdin.readline())
temp = [int(x) for x in sys.stdin.readline().split(" ")]
# 그래프 세팅
graph = [[] for _ in range(num+1)]
visited = [0] * (num+1)
for i in range(1, len(graph)):
graph[i].append(temp[i-1])
# 사이클 찾기
cnt = 0
for i in range(1, len(graph)):
if not visited[i]:
dfs(graph, visited, i)
cnt += 1
print(cnt)
728x90
반응형
'🔻PS > Baekjoon' 카테고리의 다른 글
[Baekjoon] 백준 2805 나무 자르기 Python (0) | 2024.05.11 |
---|---|
[Baekjoon] 백준 1920 수 찾기 Python (0) | 2024.05.11 |
[Baekjoon] 백준 11724 연결 요소의 개수 Python (0) | 2024.05.04 |
[Baekjoon] 백준 2178 미로 탐색 Python (0) | 2024.05.01 |
[Baekjoon] 백준 1260 DFS와 BFS Python (0) | 2024.04.28 |