ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준]13023: ABCDE - JAVA
    문제풀이/백준 2021. 3. 4. 14:19

    [백준]13023: ABCDE

    www.acmicpc.net/problem/13023

     

    13023번: ABCDE

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

    www.acmicpc.net

    풀이

    모든 경우를 탐색하는 DFS탐색 문제로, A -> B -> C -> D -> E인 관계가 있다면 1을 출력, 아니면 0을 출력하는 문제이다.

    위와 같은 연결 관계가 있다면 DFS탐색 깊이가 4가 되는 것을 이용하여 문제를 풀었다.

     

    반복문을 사용하여 시작 순서를 돌아가면서 DFS탐색을 하였고, 탐색 깊이가 4가 되는 순간 1을 출력하고 프로그램을 종료했다. 1이 출력되면 그 이후에는 더 이상 탐색하지 않아도 되기 때문이다.

     

    모든 DFS탐색 동안 1이 출력이 되지 않는다면 위와 같은 관계를 찾지 못했다는 의미이므로 0을 출력해주었다.

     

    코드

    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
    import java.util.*;
     
    public class Main {    
        
        static int n;
        static ArrayList<Integer>[] list;
        static boolean[] visited;
        
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            
            int n = scan.nextInt();
            int m = scan.nextInt();
            
            list = new ArrayList[n];
            for(int i = 0; i < n; i++) {
                list[i] = new ArrayList<>();
            }
            
            for(int i = 0; i < m; i++) {
                int a = scan.nextInt();
                int b = scan.nextInt();
                list[a].add(b);
                list[b].add(a);
            }
            
            for(int i = 0; i < n; i++) {
                visited = new boolean[n];
                dfs(i, 0);
            }
            System.out.println(0);
        }
        
        public static void dfs(int x, int len) {
            if(len == 4) {
                System.out.println(1);
                System.exit(0);
            }
            
            visited[x] = true;
            for(int i = 0; i < list[x].size(); i++) {
                int temp = list[x].get(i);
                if(visited[temp] == false) {
                    visited[temp] = true;
                    dfs(temp, len + 1);
                    visited[temp] = false;
                }
            }
        }
    }
    cs

    '문제풀이 > 백준' 카테고리의 다른 글

    [백준]2023: 신기한 소수 - JAVA  (0) 2021.03.08
    [백준]9019: DSLR - JAVA  (0) 2021.03.07
    [백준 ]5014: 스타트링크 - JAVA  (0) 2021.03.03
    [백준]1504: 특정한 최단 경로 - JAVA  (0) 2021.03.02
    [백준]2589: 보물섬 - JAVA  (0) 2021.03.02

    댓글

Designed by Tistory.