Java/백준

[Java][1260] DFS와 BFS

tmd1 2023. 2. 8. 20:17

문제:

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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

코드:

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

public class Main {
    public static ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
    public static int n;
    public static int m;
    public static int start;
    public  static boolean [] visDfs = new boolean[1005];
    public static void bfs(){
        boolean [] vis = new boolean[1005];

        Queue<Integer> q = new LinkedList<>();
        q.add(start);
        vis[start] = true;
        while(!q.isEmpty()){
            int cur = q.poll();
            System.out.print(cur+" ");
            for(int k : arr.get(cur)){
                if(vis[k]) continue;
                q.add(k);
                vis[k] = true;
            }
        }
    }
    public static  void dfs(int cur){
        visDfs[cur] = true;
        System.out.print(cur+" ");
        for(int nxt : arr.get(cur)){
            if(visDfs[nxt]) continue;
            dfs(nxt);
        }
    }
    public static void main(String[] args) throws IOException{
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt(); // node
        m = sc.nextInt(); // edge
        start = sc.nextInt(); // start num

        for(int i=0;i<=n;i++){
            arr.add(new ArrayList<>());
        }
        for(int i=0;i<m;i++){
            int u = sc.nextInt(); // node
            int v = sc.nextInt(); // edge

            arr.get(u).add(v);
            arr.get(v).add(u);
        }
        for(int i=1;i<=n;i++){
            Collections.sort(arr.get(i));
        }

        // arr complete

        dfs(start);
        System.out.println();
        bfs();

    }
}