11724번: 연결 요소의 개수

Joo·2022년 11월 14일

백준

목록 보기
9/113

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

문제

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2)

둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.

출력

첫째 줄에 연결 요소의 개수를 출력한다.

예제 입력 1

6 5
1 2
2 5
5 1
3 4
4 6

예제 출력 1

2

예제 입력 2

6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3

예제 출력 2

1

풀이

package graph_search;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main_11724 {

    private static int vertex;
    private static int edge;
    private static List<Integer>[] adjacencyList;
    private static boolean[] visited;
    private static int result;

    public static void main(String[] args) throws IOException {
        input();
        process();
        output();
    }

    private static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        vertex = Integer.parseInt(st.nextToken());
        edge = Integer.parseInt(st.nextToken());

        adjacencyList = new ArrayList[vertex + 1];
        visited = new boolean[vertex + 1];

        for (int i = 1; i <= vertex; i++) {
            adjacencyList[i] = new ArrayList<>();
        }

        for (int i = 0; i < edge; i++) {
            st = new StringTokenizer(br.readLine());

            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            adjacencyList[a].add(b);
            adjacencyList[b].add(a);
        }
    }

    private static void process() {
        for (int candidate = 1; candidate <= vertex; candidate++) {
            if (visited[candidate]) {
                continue;
            }

            dfs(candidate);
            result++;
        }
    }

    private static void dfs(int startVertex) {
        visited[startVertex] = true;

        for (Integer adjacencyVertex : adjacencyList[startVertex]) {
            if (visited[adjacencyVertex]) {
                continue;
            }

            dfs(adjacencyVertex);
        }
    }

    private static void output() {
        System.out.println(result);
    }

}

0개의 댓글