10451번: 순열 사이클
1부터 N까지 정수 N개로 이루어진 순열을 나타내는 방법은 여러 가지가 있다. 예를 들어, 8개의 수로 이루어진 순열 (3, 2, 7, 8, 1, 4, 5, 6)을 배열을 이용해 표현하면 \(\begin{pmatrix} 1 & 2 &3&4&5&6&7&8 \\ 3
www.acmicpc.net
코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N, A[];
static boolean[] visited;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// 테스트 케이스의 개수
int T = Integer.parseInt(br.readLine());
for (int t = 0; t < T; t++) {
// 순열의 크기
int N = Integer.parseInt(br.readLine());
A = new int[N + 1];
visited = new boolean[N + 1];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
int j = Integer.parseInt(st.nextToken());
A[i] = j;
}
int count = 0;
for (int i = 1; i <= N; i++) {
if (visited[i]) continue;
count++;
dfs(i);
}
sb.append(count).append("\n");
}
System.out.print(sb);
}
static void dfs(int cur) {
visited[cur] = true;
int next = A[cur];
if (!visited[next]) {
dfs(next);
}
}
}
728x90
'알고리즘 > DFS' 카테고리의 다른 글
[백준][JAVA] 2250번 트리의 높이와 너비 (0) | 2024.03.03 |
---|---|
[백준][JAVA] 1303번 전쟁 - 전투 (1) | 2024.02.09 |
[백준][JAVA] 2251번 물통 (0) | 2024.02.08 |
[백준][JAVA] 3184번 양 (2) | 2024.01.29 |
[백준][JAVA] 2210번 숫자판 점프 (0) | 2024.01.04 |