[DFS] 백준 10552 DOM JAVAAlgorithm2024. 4. 15. 15:35
Table of Contents
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)
'Algorithm' 카테고리의 다른 글
| [완전탐색] 백준 1182 부분수열의 합 JAVA (전위순회) (0) | 2024.04.18 |
|---|---|
| [DFS] 백준 11403 경로찾기 JAVA (1) | 2024.04.18 |
| [그리디] 백준 13305 주유소 JAVA (0) | 2024.04.11 |
| [DFS] 백준 11724 연결 요소의 개수 JAVA (0) | 2024.04.11 |
| [완전탐색] 백준 17484 진우의 달 여행 JAVA (0) | 2024.04.10 |