View

λ°˜μ‘ν˜•

κ³΅ν†΅μ½”λ“œ (Main)

static int N;
    static boolean adjMatrix[][];

    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt(); // μ •μ μˆ˜
        int C = sc.nextInt(); // κ°„μ„ μˆ˜

        adjMatrix = new boolean[N][N]; // 0으둜 μ΄ˆκΈ°ν™”λœ μƒνƒœ
        for (int i = 0; i < C; ++i) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            adjMatrix[to][from] = adjMatrix[from][to] = true;
        }

        bfs();
        dfs(0, new boolean[N]);

    }

BFS

πŸ’‘ μΈμ ‘λ¦¬μŠ€νŠΈ 이용

private static void bfs() {
        Queue<Integer> queue = new LinkedList<Integer>();
        boolean visited[] = new boolean[N];

        // 0 정점을 μž‘μ μœΌλ‘œ
        visited[0] = true; // 방문처리
        queue.offer(0); // 큐에 μΆ”κ°€

        while (!queue.isEmpty()) {
            int cur = queue.poll();
            System.out.print((char) (cur + 65));

            // ν˜„ μ •μ μ˜ 인접정점듀에 큐에 λ„£μ–΄μ„œ μ°¨ν›„ νƒμƒ‰ν•˜λ„λ‘ λ§Œλ“€κΈ°
            for (int i = 0; i < N; i++) {
                if (adjMatrix[cur][i] && !visited[i]) { // 방문을 ν•˜μ§€ μ•Šκ³ , ν˜„μž¬ μ •μ μ—μ„œ κ·Έ μ •μ μœΌλ‘œ 갈 수 μžˆλŠ”μ§€
                    visited[i] = true;
                    queue.offer(i);
                }
            }
        }
        System.out.println();
    }

DFS

πŸ’‘ μž¬κ·€λ‘œ κ΅¬ν˜„

private static void dfs(int current, boolean[] visited) {

        visited[current] = true; //방문처리
        System.out.print((char) (current + 65));

        for (int i = 0; i < N; ++i) {
            if (adjMatrix[current][i] && !visited[i]) {
                dfs(i, visited);
            }
        }
    }
}
λ°˜μ‘ν˜•
Share Link
reply
λ°˜μ‘ν˜•
Β«   2024/12   Β»
일 μ›” ν™” 수 λͺ© 금 ν† 
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31