[백준] 1260 DFS와 BFS.Java

9999·2023년 6월 6일
0

BOJ

목록 보기
105/128

문제

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

입력

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

출력

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

풀이

  • DFS는 idx에 따라 순서를 확인한다.
  • BFS는 cnt증가에 따라 확인한다.
  • int[] node는 그냥 순서 확인용이라서 무시해도 무방하다.
  • 둘 다 순회 전, Collections.sort()로 정렬해준다.
import java.io.*;
import java.util.*;
public class Main {
    static List<Integer>[] graph;
    static int N, M, V;
    static boolean[] visited;
    static int[] node;
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        V = Integer.parseInt(st.nextToken());
        graph = new ArrayList[N+1];
        visited = new boolean[N+1];
        for (int i = 0; i <= N; i++)
            graph[i] = new ArrayList<>();

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            graph[x].add(y);
            graph[y].add(x);
        }
        node = new int[N+1];
        DFS(V, 1);
        sb.append('\n');
        BFS(V);
        System.out.println(sb);
    }
    public static void DFS(int v, int idx) {
        visited[v] = true;
        node[idx] = v;
        sb.append(v).append(" ");
        Collections.sort(graph[v]);
        for (int i: graph[v]) {
            if (!visited[i]) {
                DFS(i, idx+1);
            }
        }
    }
    public static void BFS(int v) {
        visited = new boolean[N+1];
        Queue<Integer> q = new LinkedList<>();
        int cnt = 0;
        q.add(v);
        visited[v] = true;
        while(!q.isEmpty()) {
            int n = q.poll();
            cnt++;
            node[cnt] = n;
            sb.append(n).append(" ");
            Collections.sort(graph[n]);
            for (int i: graph[n]) {
                if (!visited[i]) {
                    visited[i] = true;
                    q.add(i);
                }
            }
        }
    }

}

0개의 댓글