본문 바로가기

PS/Problems

[Java] 백준 1389번 케빈 베이컨 - BFS

bfs 구현에 큐도 쓸줄 모르던 시절은 안녕~

package class3;

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

public class s1_1389{
    static List<HashSet<Integer>> table = new ArrayList<>();
    static Queue<Integer> q = new LinkedList<>();
    static boolean[] check;
    static int sum;
    public static void main(String[] args){
        FastScanner fs = new FastScanner();
        PrintWriter pw = new PrintWriter(System.out);

        int N = fs.nextInt(), M = fs.nextInt();
        check = new boolean[N + 1];
        for (int i=0;i<N+1;i++) table.add(new HashSet<>());
        for (int i=0;i<M;i++){
            int a = fs.nextInt(), b = fs.nextInt();
            table.get(a).add(b);
            table.get(b).add(a);
        }
        int min = Integer.MAX_VALUE;
        int num = 1;
        for (int i=1;i<N+1;i++){
            Arrays.fill(check, false);
            check[i] = true;
            q.add(i);
            sum = 0;
            bfs(0);

            if (sum < min){
                min = sum;
                num = i;
            }
        }
        pw.println(num);
        pw.close();
    }

    static void bfs(int cnt){
        int size = q.size();
        if (size == 0) return;

        for (int i=0;i<size;i++){
            int node = q.poll();
            sum += cnt;
            for (Integer k : table.get(node)){
                if (!check[k]){
                    check[k] = true;
                    q.add(k);
                }
            }
        }

        bfs(cnt + 1);
    }

    static void sort(int[] a){
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a) L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++) a[i] = L.get(i);
    }

    static class FastScanner{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");
        String next(){
            while (!st.hasMoreTokens()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt(){
            return Integer.parseInt(next());
        }

        int[] readArray(int n){
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        long nextLong(){
            return Long.parseLong(next());
        }
    }
}