백준 DFS와 BFS(1260) java

연도리·2023년 1월 16일
0

algorithmStudy

목록 보기
10/11

문제

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

입력

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

출력

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

예제 입력 1

4 5 1
1 2
1 3
1 4
2 4
3 4

예제 출력 1

1 2 4 3
1 2 3 4

예제 입력 2

5 5 3
5 4
5 2
1 2
3 4
3 1

예제 출력 2

3 1 2 5 4
3 1 4 2 5

예제 입력 3

1000 1 1000
999 1000

예제 출력 3

1000 999
1000 999

try1

import java.io.*;
import java.util.*;
public class Main{
    public static int N;
    public static int M;
    public static int V;
    public static int[][] arr;
    public static boolean[] check;
    public static Queue<Integer> q = new LinkedList<>();

    public static void main(String args[]) throws IOException {

         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
         N = Integer.parseInt(st1.nextToken());
         M = Integer.parseInt(st1.nextToken());
         V = Integer.parseInt(st1.nextToken());

         arr = new int[N+1][N+1];
         check = new boolean[N+1];

         for(int i = 0; i < M; i++){
            StringTokenizer st2 = new StringTokenizer(br.readLine(), " ");

            int a = Integer.parseInt(st2.nextToken());
            int b = Integer.parseInt(st2.nextToken());
            arr[a][b] = arr[b][a] = 1;
         }
         
         dfs(V);
         check = new boolean[N+1];
         System.out.println();
         bfs(V);
         
    }

    public static void dfs(int num){
        check[num] = true;
        System.out.print(num + " ");

        for(int j = 1; j <= N; j++){
            if(arr[num][j] == 1 && !check[j]){
                dfs(j);
            }
        }
    }

    public static void bfs(int num){
        q.add(num);
        check[num] = true;

        while(!q.isEmpty()){
            num = q.poll();
            System.out.print(num + " ");

            for(int i = 1; i <= N; i++){
                if(arr[num][i] == 1 && !check[i]){
                    q.add(i);
                    check[i] = true;
                }
            }
        }
    }
}

note

  • DFS(깊이우선)는 스택/재귀함수, BFS(너비우선)는 큐를 활용해서 구현한다.
profile
아장아장 초보 개발자

0개의 댓글