[BOJ 2668] ์ซ์๊ณ ๋ฅด๊ธฐ
1. ๋ฌธ์ : https://www.acmicpc.net/problem/2668
2. ํ์ด
์ธ์ดํด ์ฐพ๋๊ฒ ์ค์ํ ๋ฌธ์
3. ์ฝ๋
import java.util.*;
public class Main {
static ArrayList<Integer> list;
static boolean[] visited;
static int[] num;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//n๊ฐ์ ์ ์๋ฅผ ์
๋ ฅ๋ฐ๋๋ค.
int n = scan.nextInt();
num = new int[n + 1];
for(int i = 1; i <= n; i++) {
num[i] = scan.nextInt();
}
//์์๋๋ก ์ฌ์ดํด์ด ๋ฐ์ํ๋์ง dfs๋ก ํ์ธํ๋ค.
list = new ArrayList<>();
visited = new boolean[n + 1];
for(int i = 1; i <= n; i++) {
visited[i] = true;
dfs(i, i);
visited[i] = false;
}
Collections.sort(list); //์์ ์ ๋ถํฐ ์ถ๋ ฅํ๋ฏ๋ก ์ ๋ ฌํ๋ค.
System.out.println(list.size());
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static void dfs(int start, int target) {
if(visited[num[start]] == false) {
visited[num[start]] = true;
dfs(num[start], target);
visited[num[start]] = false;
}
if(num[start] == target) list.add(target); //์ฌ์ดํด ๋ฐ์์ ํด๋น ์ซ์๋ฅผ list์ ๋ด์์ค๋ค.
}
}
'๐ป Coding Problems Solving > DFS | BFS | Backtracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ 1103] ์คํํธ๋งํฌ (0) | 2023.08.11 |
---|---|
[BOJ 9466] ํ ํ๋ก์ ํธ (0) | 2023.08.01 |
[ํ๋ก๊ทธ๋๋จธ์ค] ๊ด๋ฌผ์บ๊ธฐ (์๋ฐ java) (0) | 2023.05.18 |
[BOJ 17086] ์๊ธฐ์์ด2 (0) | 2023.05.16 |
[BOJ 17086] ์ด๋ชจํฐ์ฝ (0) | 2023.05.16 |
์ต๊ทผ๋๊ธ