https://www.acmicpc.net/problem/11581
11581번: 구호물자
서기 2050년 엄청나게 강력한 폭풍이 인천을 강타했다. 강력한 폭풍의 영향으로 모든 사람은 대피소로 대피하였으며, 많은 도로가 유실되었다. 그나마 남아있는 도로도 모든 표지판과 가로등이
www.acmicpc.net
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_11581 {
private static final String CYCLE = "CYCLE";
private static final String NOT_CYCLE = "NO CYCLE";
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());
List<Integer>[] map = new List[n+1];
for(int i = 1 ; i < n ; i++){
map[i] = new LinkedList<>();
int num = stoi.apply(br.readLine());
st = new StringTokenizer(br.readLine());
for(int j = 0 ; j < num ; j++){
int next = stoi.apply(st.nextToken());
map[i].add(next);
}
}
boolean[] visited = new boolean[n+1];
if(!detectCycle(map,1,visited,n)){
System.out.println(CYCLE);
}else{
System.out.println(NOT_CYCLE);
}
}
private static boolean detectCycle(List<Integer>[] map,int now,boolean[] visited, int n){
if(now == n){
return true;
}
visited[now] = true;
boolean result = true;
for(int i = 0 ; i < map[now].size() ; i++){
int next = map[now].get(i);
if(visited[next]){
return false;
}
if(!detectCycle(map,next,visited,n)){
result = false;
}
}
visited[now] = false;
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 k보다 큰 구간 (JAVA) (0) | 2023.01.19 |
---|---|
백준 6159번 코스튬 파티 (JAVA) (0) | 2023.01.19 |
백준 15558번 점프 게임 (JAVA) (0) | 2023.01.16 |
프로그래머스 귤 고르기(JAVA) (0) | 2023.01.15 |
프로그래머스 잘라서 배열로 저장하기 (JAVA) (0) | 2023.01.14 |