๐Ÿ“– [๋ฐฑ์ค€์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด] Q.10451 ์ˆœ์—ด ์‚ฌ์ดํด ๋ฌธ์ œ ํ’€์ด - java

๐Ÿ“– ๋ฌธ์ œ

https://www.acmicpc.net/problem/10451

๐Ÿ” ์ ‘๊ทผ๋ฒ•

Q.10451 ์ˆœ์—ด ์‚ฌ์ดํด ๋ฌธ์ œ ํ’€์ด์ž…๋‹ˆ๋‹ค.

๋ฌธ์ œ์—์„œ ์ˆœ์—ด ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง€๊ณ 

์ด ์ˆœ์—ด ๊ทธ๋ž˜ํ”„์—์„œ ์ˆœ์—ด ์‚ฌ์ดํด์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋ช‡๊ฐœ์ธ์ง€๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ˆœ์—ด ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค๊ณ 

๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ dfs๋ฅผ ํ†ตํ•ด์„œ ํ’€์ด๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

dfs๋ฅผ ํ†ตํ•ด ํƒ์ƒ‰์„ ํ•˜๋‹ค ์ด๋ฏธ ๋ฐฉ๋ฌธ ํ–ˆ๋˜ ๊ณณ์— ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜๋ คํ•œ๋‹ค๋ฉด

์‚ฌ์ดํด์ด๋ฏ€๋กœ ์‚ฌ์ดํด ๊ฐœ์ˆ˜๋ฅผ ๋Š˜๋ ค์ค๋‹ˆ๋‹ค.

์ตœ์ข…์ ์œผ๋กœ ์‚ฌ์ดํด์˜ ๊ฐœ์ˆ˜๋ฅผ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ’ป ์ฝ”๋“œ

package problem.bfsdfs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main_10451 {
    static int count = 0;
    static int t,n;
    static List<List<Integer>> adjList;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
        input();
    }
    private static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        t = Integer.parseInt(br.readLine());
        for(int num=0; num<t; num++){
            count = 0;
            adjList = new ArrayList<>();
            n = Integer.parseInt(br.readLine());
            visited = new boolean[n+1];
            for(int i=0; i<=n; i++){
                adjList.add(new ArrayList<>());
            }
            String temp[] = br.readLine().split(" ");
            for(int i=1; i<=n; i++){
                int v = Integer.parseInt(temp[i-1]);
                adjList.get(i).add(v);
            }
            for(int i=1; i<=n; i++){
                if(!visited[i]){
                    dfs(i);
                }
            }
            System.out.println(count);
         }
        br.close();
    }

    private static void dfs(int start){
        visited[start] = true;
        for(int next : adjList.get(start)){
            if( !visited[next] ){
                dfs(next);
            }
            else{
                count++;
                return;
            }
        }
    }
}

Written on April 8, 2021