PS/백준

백준 촌수 계산(2644)

팡세영 2022. 6. 27. 03:02

촌수 계산(2644)


풀이

  • bfs를 통해 깊이를 세주면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

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

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


public class Main {
    static int arr[][];
    static boolean visited[];
    static int depth[];

    public static void main(String args[]) throws IOException {
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();   // 전체 사람 수 (정점 수)
        int findX = sc.nextInt();
        int findY = sc.nextInt();
        int m = sc.nextInt();  // 부모 자식 관계 수 (간선 수)

        arr = new int[n+1][n+1];
        visited = new boolean[n+1];
        depth = new int[n+1];

        for(int i=0; i<m; i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            arr[a][b] = 1;
            arr[b][a] = 1;
        }

        bfs(findX, n);

        if(depth[findY] == 0)
            System.out.println("-1");
        else
           System.out.println(depth[findY]);

    }

    public static void bfs(int start,int n) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);

        while(!queue.isEmpty()){
            int pos = queue.poll();

            for(int i=1; i<=n; i++){
                if(!visited[i] && arr[pos][i] == 1){
                    queue.add(i);
                    visited[i] = true;
                    depth[i] = depth[pos] + 1;
                }
            }
        }


    }

}