백준 17204번 죽음의 게임

이상민·2023년 9월 27일
0

알고리즘

목록 보기
64/128
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class The_Game_Of_Death {
    static int N,K;
    static boolean[] visited;
    static int[] person;
    static int count = 0;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());
        person = new int[N];
        visited = new boolean[N];
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            person[i] = Integer.parseInt(st.nextToken());
        }
        visited[0] = true;
        dfs(person[0]);

    }
    public static void dfs(int num){

        if(visited[num]){
            System.out.println(-1);
            return;
        }
        count++;
        if(num == K){
            System.out.println(count);
            return;
        }
        visited[num] = true;
        dfs(person[num]);
    }
}

풀이방법

📢 이 풀이의 핵심은 한사람씩 호출하다가 K가 나오면 멈춰야 한다.
K가 나오기 전에 이미 호출한사람을 부른다면 영원히 K가 나오지 않는다.
이를 바탕으로 구현한다.

  1. 0번 부터 지목한 사람을 인수로 재귀함수를 호출한다.
  2. 호출한 사람을 visited 체크하고, 다음 사람을 인수로 재귀함수를 호출한다.
  3. 이미 호출한 사람을 부른다면 -1출력한다.
  4. K가 호출되면 그때의 count를 출력한다.
profile
개린이

0개의 댓글