개발자-H 입니다.

BOJ - 연결 요소의 개수 (11724) 본문

Algorithm/문제 풀이

BOJ - 연결 요소의 개수 (11724)

개발자-H 2021. 8. 7. 12:07

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

 

11724번: 연결 요소의 개수

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주

www.acmicpc.net

 

  • 그래프를 탐색하며 연결 요소를 구하는 문제이다.
    • DFS 탐색 횟수를 카운팅하여 연결 요소를 개수를 구했다.
    • 그래프 기본 문제 유형인듯 
package baekjoon;

import java.lang.*;
import java.util.*;


public class Main {
    public static final Scanner scanner = new Scanner(System.in);

    public static final int NOT_VISITED = -1;

    public static void main(String[] args) throws Exception {
        int V = scanner.nextInt();
        int M = scanner.nextInt();

        ArrayList<Integer>[] adj = new ArrayList[V + 1];
        int[] visited = new int[V + 1];
        Arrays.fill(visited, NOT_VISITED);

        for (int i = 0; i <= V; i += 1) {
            adj[i] = new ArrayList<>();
        }

        for (int i = 0; i < M; i += 1) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            adj[u].add(v);
            adj[v].add(u);
        }

        Integer connected = 0;
        for (int i = 1; i <= V; i++) {
            if (visited[i] == NOT_VISITED) {
                connected += 1;
                dfsRecursive(i, connected, visited, adj);
            }
        }

        System.out.println(connected);
    }

    private static void dfsRecursive(int currentNode, Integer connected, int[] visited, ArrayList<Integer>[] adj) {
        visited[currentNode] = connected;
        for (int i = 0; i < adj[currentNode].size(); i++) {
            Integer next = adj[currentNode].get(i);
            if (visited[next] == NOT_VISITED) {
                dfsRecursive(next, connected, visited, adj);
            }
        }
    }
}

'Algorithm > 문제 풀이' 카테고리의 다른 글

구름 - 길찾기 (다이아몬드)  (0) 2021.08.08
LeetCode - FloodFile  (0) 2021.08.07
BOJ - 섬의 개수 (4963)  (0) 2021.08.07
BOJ - 단지번호붙이기 (2667)  (0) 2021.08.07
프로그래머스 - 가장 먼 노드  (0) 2021.08.04
Comments