본문 바로가기

독서/알고리즘

연결 요소의 개수

728x90

출력

이 문제는 간선으로 연결된 정점을 모두 탐색하며, 그래프의 개수를 구하는 문제다.

정답

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

public class Main {
    
    public static void main(String[] args) throws Exception {
        final var br = new BufferedReader(new InputStreamReader(System.in));
        final var bw = new BufferedWriter(new OutputStreamWriter(System.out));

        final String[] nm = br.readLine().split(" ");
        final int n = Integer.parseInt(nm[0]);
        final int m = Integer.parseInt(nm[1]);
        final Graph graph = new Graph(n);
        for (int i = 0; i < m; i++) {
            final String[] uv = br.readLine().split(" ");
            final int u = Integer.parseInt(uv[0]) - 1;
            final int v = Integer.parseInt(uv[1]) - 1;
            graph.addEdge(u, v);
        }
        
        bw.write(String.valueOf(graph.countConnectedComponents()));

        bw.flush();
        bw.close();
        br.close();
    }

    private static class Graph {
        private final int n;
        private final List<List<Integer>> adj;

        public Graph(int n) {
            this.n = n;
            this.adj = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                this.adj.add(new ArrayList<>());
            }
        }

        public void addEdge(int u, int v) {
            this.adj.get(u).add(v);
            this.adj.get(v).add(u);
        }

        public int countConnectedComponents() {
            final boolean[] visited = new boolean[n];
            int count = 0;
            for (int i = 0; i < n; i++) {
                if (!visited[i]) {
                    dfs(i, visited);
                    count++;
                }
            }
            return count;
        }

        private void dfs(int u, boolean[] visited) {
            visited[u] = true;
            for (int v : adj.get(u)) {
                if (!visited[v]) {
                    dfs(v, visited);
                }
            }
        }

        private void bfs(int u, boolean[] visited) {
            final Queue<Integer> q = new LinkedList<>();
            q.offer(u);
            visited[u] = true;
            while (!q.isEmpty()) {
                final int v = q.poll();
                for (int w : adj.get(v)) {
                    if (!visited[w]) {
                        q.offer(w);
                        visited[w] = true;
                    }
                }
            }
        }
    }
}

'독서 > 알고리즘' 카테고리의 다른 글

친구  (0) 2023.12.31
백준 1965 상자넣기  (0) 2022.01.10
백준 2110 공유기 설치  (0) 2021.12.30
백준 23352 방탈출  (0) 2021.12.28
백준 1188 음식 평론가  (0) 2021.12.27