ABOUT ME

Today
Yesterday
Total
  • 백준 dfs, bfs
    공부공부 2022. 3. 1. 14:25
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    
    class CodingTest {
        static int[][] arr;
        static boolean[] visited;
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int N = scan.nextInt();
            int M = scan.nextInt();
            int V = scan.nextInt();
    
            arr = new int[N+1][N+1];
            for(int i=0; i < M; i++){
                int a = scan.nextInt();
                int b = scan.nextInt();
                arr[a][b] = 1;
                arr[b][a] = 1;
            }
    
            visited = new boolean[N+1];
            dfs(V);
    
            System.out.println();
    
            visited = new boolean[N + 1];
            bfs(V);
        }
    
        public static void dfs(int V){
            visited[V] = true;
            System.out.print(V + " ");
    
            if(V == arr.length) {
                return;
            }
            for(int j = 1; j < arr.length; j++) {
                //연결은 되어있는데, 방문하지 않았다면 재귀
                if(arr[V][j] == 1 && visited[j] == false) {
                    dfs(j);
                }
            }
        }
    
        public static void bfs(int V){
            Queue<Integer> que = new LinkedList<Integer>();
    
            que.add(V);
            visited[V] = true;
            System.out.print(V + " ");
    
            while(!que.isEmpty()) {
                int temp = que.poll();
                for(int i = 1; i < arr.length; i++) {
                    if(arr[temp][i] == 1 && visited[i] == false) {
                        que.add(i);
                        visited[i] = true;
                        System.out.print(i + " ");
                    }
                }
            }
        }
    }

    '공부공부' 카테고리의 다른 글

    백준 11004 K번째 수  (0) 2022.04.13
    백준 17298 오큰수 java  (0) 2022.04.12
    브라우저  (0) 2022.01.25
    자바스크립트에 대해서 1  (0) 2022.01.23
    스크롤 하면 섹션에 따라 nav 메뉴가 활성화 되도록  (0) 2022.01.19
Designed by Tistory.