Algorithm

[DFS] 백준 10552 DOM JAVA

EllaCoo 2024. 4. 15. 15:35
package com.test.dfs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DFS_3_10552 {
    static boolean[] visited = new boolean[100000 + 1]; //idx: 방문한 채널
    static int[] toFavChannel = new int[100000 + 1]; //idx: 싫어하는 채널, value: 좋아하는 채널
    static int count = 0;
    public static void main(String[] args) throws IOException {
        // [DFS] 백준 10552 DOM JAVA
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        int N = Integer.parseInt(input[0]); // 1~10^5
        int M = Integer.parseInt(input[1]); // 1~10^5
        int P = Integer.parseInt(input[2]); // 1~M

        for (int i = 0 ; i < N ; i++) {
            input = br.readLine().split(" ");
            int favChannel = Integer.parseInt(input[0]);
            int hateChannel = Integer.parseInt(input[1]);
            if (toFavChannel[hateChannel] == 0) toFavChannel[hateChannel] = favChannel;
        }
        changeChannel(P);
        System.out.print(count);
    }
    static public void changeChannel(int ch) {
        if (visited[ch])  {
            count = -1;
        } else if (toFavChannel[ch] != 0) {
            count++;
            visited[ch] = true;
            changeChannel(toFavChannel[ch]);
        }
    }
}
시간복잡도 : O(N)