DFS와 BFS

개굴이·2023년 10월 12일
0

코딩테스트

목록 보기
47/58
post-thumbnail

백준 1260번 DFS와 BFS

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

입력

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

출력

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

소스

import java.io.*;
import java.util.*;

public class Main {

    static ArrayList<ArrayList<Integer>> graph;
    static boolean[] visited;
    static Queue<Integer> queue;

    public static void main(String[] args) throws IOException {
        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 start = Integer.parseInt(st.nextToken()); // 시작점
        graph = new ArrayList<>();
        for(int i = 0; i < N + 1; i++)
            graph.add(i, new ArrayList<>());
        for(int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int input1 = Integer.parseInt(st.nextToken());
            int input2 = Integer.parseInt(st.nextToken());
            graph.get(input1).add(input2); // 양방향
            graph.get(input2).add(input1);
        }
        for(ArrayList list : graph) // 정렬 필요
            if(!list.isEmpty())
                list.sort(new Comparator() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        return (int) o1 - (int) o2;
                    }
                });
        visited = new boolean[N + 1];
        DFS(start);
        System.out.println();
        Arrays.fill(visited, false);
        queue = new LinkedList<>();
        BFS(start);
    }
    public static void DFS(int num) {
        visited[num] = true;
        System.out.print(num + " ");
        for(int i : graph.get(num))
            if(!visited[i])
                DFS(i);
    }
    public static void BFS(int num) {
        queue.add(num);
        visited[num] = true;
        while(!queue.isEmpty()) {
            int now = queue.poll();
            System.out.print(now + " ");
            for(int i : graph.get(now))
                if(!visited[i]) {
                    queue.add(i);
                    visited[i] = true;
                }
        }
    }
}

0개의 댓글