μ½”λ”©ν…ŒμŠ€νŠΈ

[BFS] 14. κ·Έλž˜ν”„ μ΅œλ‹¨ 거리

μ‹œνλ¦¬ν‹°μ§€ν˜Έ 2024. 2. 10. 16:29

<<풀이>>

 

이 λ¬Έμ œλŠ” 1번 μ •μ μ—μ„œ 각 μ •μ κΉŒμ§€μ˜ μ΅œμ†Œ κ°„μ„  수λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμ΄λ‹€.

 

Level둜 ν’€ μˆ˜λ„ μžˆμ§€λ§Œ, κ·Έ 외에 disλΌλŠ” 배열을 μ‚¬μš©ν–ˆλ‹€. μ΄λŠ” 1μ—μ„œ λΆ€ν„° ν•΄λ‹Ή κ°’κΉŒμ§€ 였기 μœ„ν•œ κ°„μ„  의 수λ₯Ό μ €μž₯해두고 μžˆλ‹€.

 

그리고 아직 등둝이 λ˜μ§€ μ•Šμ€ 값듀을 μ—°κ²°λ˜μ–΄ 있던 이전 κ°’λ“€ κΉŒμ§€ 였기 κΉŒμ§€μ˜ κ°„μ„ μ˜ μˆ˜μ— + 1을 ν•΄μ€€λ‹€.

 

κ·Έλ ‡κ²Œ ν•΄μ„œ μ΅œμ’…μ μœΌλ‘œ dis의 λ°μ΄ν„°λŠ” 인덱슀 값을 1μ—μ„œ 2, 3, 4, 5 둜 νŠΉμ • μœ„μΉ˜λ‘œ κ°„λ‹€κ³  λͺ…ν™•ν•˜κ²Œ ν‘œμ‹œν•˜κ³  κ·Έ λ•Œ κ°„μ„  값을 κ°€μ§€κ³  μžˆλ‹€.

 

*인덱슀 값이 μ‹€μ œ κ°’ 1, 2, 3 λ“±μœΌλ‘œ ν‘œν˜„ν•΄μ„œ λͺ…ν™•ν•˜κ²Œ ν•˜κΈ° μœ„ν•΄μ„œ 초기 λ°°μ—΄ μ„ μ–Έ λΆ€ν„° [n] 이 μ•„λ‹Œ [n + 1]둜 μ§€μ •ν–ˆλ‹€.

 

*λ§Œμ•½ 1 -> 2둜 κ°€λŠ” 것도 μžˆμ§€λ§Œ 1 -> 3 -> 2둜 κ°€λŠ” 것도 μžˆλ‹€λ©΄ μ–΄λ–»κ²Œ μ΅œμ†Œ 간선인 것을 κ΅¬λΆ„ν•˜μ§€? λΌλŠ” 생각을 μ΄ˆκΈ°μ— ν–ˆλŠ”λ° μƒκ°ν•΄λ³΄λ‹ˆκΉŒ ch[] λΌλŠ” μ²΄ν¬ν•˜λŠ” λ°°μ—΄λ‘œ ν†΅ν•΄μ„œ 이미 κ°„ 곳은 1둜 되기 λ•Œλ¬Έμ— 사전에 1 -> 2둜 κ°„ 것이 μžˆλ‹€λ©΄ 1 -> 3 -> 2둜 κ°€λŠ” 것은 λΊ„ 수 μžˆλŠ” 것이닀.

 

 

 

 

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Main {
    static int n, m;
    static ArrayList<ArrayList<Integer>> graph;
    static int[] ch, dis;
    public void BFS(int v) {
        Queue<Integer> queue = new LinkedList<>();
        ch[v] = 1;
        dis[v] = 0;
        queue.offer(v);
        while (!queue.isEmpty()) {
            int cv = queue.poll();
            for(int nv : graph.get(cv)) {
                if (ch[nv] == 0) {
                    ch[nv] = 1;
                    queue.offer(nv);
                    dis[nv] = dis[cv] + 1;
                }
            }
        }
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        graph = new ArrayList<ArrayList<Integer>>();
        for (int i = 0; i <= n; i++) {
            graph.add(new ArrayList<Integer>());
        }
        ch = new int[n + 1];
        dis = new int[n + 1];
        for (int i = 0; i < m; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            graph.get(a).add(b);
        }
        T.BFS(1);
        for (int i = 2; i <= n; i++) {
            System.out.println(i + " : " + dis[i]);

        }
    }
}

 

μ—¬κΈ°κΉŒμ§€ DFS BFS 의 μ—¬λŸ¬κ°€μ§€ 문제 ν˜•μ‹μ„ μ ‘ν•΄λ³΄μ•˜λ‹€. μ΄ν•΄λŠ” ν–ˆμ§€λ§Œ μ•„μ§κΉŒμ§€ μ™„λ²½νžˆ λ‚΄ 것은 μ•„λ‹Œ 것 κ°™λ‹€. 이제 λΆ€ν„° 본격적으둜 κΈ°μΆœμ„ ν’€μ–΄ 볼텐데 μ™„μ „νžˆ λ‚΄ 것이 될 수 μžˆλ„λ‘ κ³΅λΆ€ν•΄λ³΄μž!!