• [백준][JAVA] DFS와 BFS

    2025. 1. 2.

    by. hyunji1109

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

     

    문제

    그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

     

    입력

    첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

     

    출력

    첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

     


     

     

    import java.util.*;
    
    public class Main {
        static List<Integer>[] graph;
        static boolean[] visited;
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int m = sc.nextInt();
            int start = sc.nextInt(); 
    
            graph = new ArrayList[n + 1];
            visited = new boolean[n + 1];
    
            for (int i = 1; i <= n; i++) {
                graph[i] = new ArrayList<>();
            }
    
            for (int i = 0; i < m; i++) {
                int u = sc.nextInt();
                int v = sc.nextInt();
                graph[u].add(v);
                graph[v].add(u);
            }
    
            for (int i = 1; i <= n; i++) {
                Collections.sort(graph[i]);
            }
    
            dfs(start);
            System.out.println();
            Arrays.fill(visited, false);
            bfs(start);
        }
    
        static void dfs(int node) {
            visited[node] = true;
            System.out.print(node + " ");
            for (int next : graph[node]) {
                if (!visited[next]) {
                    dfs(next);
                }
            }
        }
    
        static void bfs(int start) {
            Queue<Integer> queue = new LinkedList<>();
            queue.add(start);
            visited[start] = true;
    
            while (!queue.isEmpty()) {
                int node = queue.poll();
                System.out.print(node + " ");
                for (int next : graph[node]) {
                    if (!visited[next]) {
                        queue.add(next);
                        visited[next] = true;
                    }
                }
            }
        }
    }

     

     

     

    'CT > 백준' 카테고리의 다른 글

    [백준][JAVA] 팰린드롬 만들기  (1) 2025.01.04
    [백준][JAVA] 수들의 합 2  (1) 2025.01.03
    [백준][JAVA] 걷기  (0) 2024.12.31
    [백준][JAVA] 청기 백기  (1) 2024.12.28
    [백준][JAVA] 병든 나이트  (1) 2024.12.27

    댓글