<BOJ> 2644 자바 (촌수계산)

2024. 7. 22. 21:24Algorithm/BOJ

반응형

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

백준 2644 자바
신라호텔 라운지
The Shilla hotel Lounge

 

 

풀이 시간 

 - 25M

 

풀이 과정

 - 양방향 그래프

 - 시작 사람 노드에서 출발해 끝사람 노드를 마주치면 출력, 못마주치면 -1 출력

 - visited 배열 체크

풀이 코드

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class b2644 {
    static int s, e, dist;
    static boolean isGoal = false;
    static ArrayList<Integer>[] parent;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int all = Integer.parseInt(br.readLine());
        parent = new ArrayList[all+1];
        for (int i = 1; i <= all; i++) {
            parent[i] = new ArrayList<>();
        }

        StringTokenizer st = new StringTokenizer(br.readLine());

        s = Integer.parseInt(st.nextToken());
        e = Integer.parseInt(st.nextToken());

        int m = Integer.parseInt(br.readLine());
        for (int i = 0; i < m; i++) {
            st = new StringTokenizer(br.readLine());
            int p = Integer.parseInt(st.nextToken());
            int c = Integer.parseInt(st.nextToken());
            parent[p].add(c);
            parent[c].add(p);
        }

        Queue<int[]> q = new LinkedList<>();
        boolean[] visited = new boolean[all + 1];
        q.add(new int[]{s,0});   // 시작점, 촌수

        while (!q.isEmpty()) {
            int[] arr = q.poll();
            for (int i : parent[arr[0]]) {
                if (i == e) {
                    System.out.println(arr[1] + 1);
                    return;
                }
                if(visited[i]) continue;
                visited[i] = true;
                q.add(new int[]{i, arr[1] + 1});
            }
        }
        System.out.println(-1);


    }

}
반응형

'Algorithm > BOJ' 카테고리의 다른 글

<BOJ> 1655 자바 (가운데를 말해요)  (0) 2024.07.29
<BOJ> 12865 자바 (평범한 배낭)  (0) 2024.07.28
<BOJ> 2667 자바 (단지번호붙이기)  (0) 2024.07.21
<BOJ> 17142 자바(연구소3)  (0) 2024.07.21
<BOJ> 14502 자바 (연구소)  (4) 2024.07.20