CS/알고리즘_문제풀이(자바)

ABCDE

Jedy_Kim 2021. 9. 15. 13:10
728x90

https://www.acmicpc.net/problem/13023

 

13023번: ABCDE

문제의 조건에 맞는 A, B, C, D, E가 존재하면 1을 없으면 0을 출력한다.

www.acmicpc.net

 

// 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;
import java.io.*;
 
public class Main{
  
  public static boolean flag = false;
  
  public static void getResult(int x, int N, int M, List<ArrayList<Integer>> listGraph, int[]check, int idx) {
    if(flag) return;
    
    if(idx >= 5) {
      flag = true;
    } else {
      for(int j=0; j<listGraph.get(x).size(); j++) {
        if(check[listGraph.get(x).get(j)] == 0) {
          check[listGraph.get(x).get(j)] = 1
          getResult(listGraph.get(x).get(j), N, M, listGraph, check, idx+1);
          check[listGraph.get(x).get(j)] = 0
        }
        
      }
    } 
    
  }
  
  public static void main(String[] args) throws Exception {
 
    // Please Enter Your Code Here
    BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());
    
    int N = Integer.parseInt(st.nextToken());
    int M = Integer.parseInt(st.nextToken());
    
    int[] result = new int[N];
    int[] check  = new int[N];
    
    // 1.인접리스트를 구한다.
    List<ArrayList<Integer>> listGraph = new ArrayList<>();;
    for(int i=0; i<N; i++) {
      listGraph.add(new ArrayList<Integer>()); 
    }
    for(int i=0; i<M; i++) {
      st = new StringTokenizer(br.readLine());
      int x = Integer.parseInt(st.nextToken());
      int y = Integer.parseInt(st.nextToken());
      
      listGraph.get(x).add(y);
      listGraph.get(y).add(x);
    } 
    
    // 2.DFS 탐색을 하여 깊이가 4이상이면 1, 아니면 0을 출력한다.
    for(int i=0; i<N; i++)
      getResult(i, N, M, listGraph, check, 0);
    
    if(flag) {
      System.out.println(1);  
    } else {
      System.out.println(0);
    }
    
  }
}
cs

 

반응형

'CS > 알고리즘_문제풀이(자바)' 카테고리의 다른 글

최소공배수  (0) 2021.09.17
DFS와 BFS  (0) 2021.09.15
N과 M (2)  (0) 2021.09.15
N과 M (1)  (0) 2021.09.15
문자열 포함관계 조사  (0) 2021.09.14