https://www.acmicpc.net/problem/21937
21937번: 작업
민상이가 작업할 개수 $N$와 작업 순서 정보의 개수 $M$이 공백으로 구분되어 주어진다. 두 번째줄부터 $M + 1$ 줄까지 작업 $A_i$와 작업 $B_i$가 공백으로 구분되어 주어진다. 이때 두 값의 의미는 작
www.acmicpc.net
저는 dfs를 통해 문제를 해결했습니다.
저는 방향을 반대로 하는 그래프를 그리고 dfs로 탐색하고 어디어디 탐색했는지를 체크하여 답을 구하였습니다.
package BOJ.dfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_21937 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int m = stoi.apply(st.nextToken());
List<Integer>[] map = new List[n+1];
for(int i = 0 ; i < n+1 ; i++){
map[i] = new LinkedList<>();
}
for(int i = 0 ; i < m ; i++){
st = new StringTokenizer(br.readLine());
int a = stoi.apply(st.nextToken());
int b = stoi.apply(st.nextToken());
map[b].add(a);
}
int start = stoi.apply(br.readLine());
boolean[] visited = new boolean[n+1];
cal(start,map,visited,n);
int result = 0;
for(int i = 1 ; i <= n ; i++){
if(visited[i] && i != start){
result++;
}
}
System.out.println(result);
}
private static void cal(int start, List<Integer>[] map, boolean[] visited,int n) {
visited[start] = true;
for(int next : map[start]){
if(!visited[next]){
cal(next,map,visited,n);
}
}
return ;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 베스트앨범 (JAVA) (0) | 2023.06.22 |
---|---|
백준 6146번 신아를 만나러 (JAVA) (0) | 2023.06.21 |
백준 11403번 경로 찾기 (JAVA) (0) | 2023.06.19 |
백준 25634번 전구 상태 뒤집기 (JAVA) (0) | 2023.06.18 |
백준 28107번 회전초밥 (JAVA) (0) | 2023.06.17 |