ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 11724 : 연결 요소의 개수
    Solve Algorithms/BFS, DFS 2020. 4. 19. 15:13
    728x90

    출처 : 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) 같은 간선은 한 번만 주어진다.

    출력

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


    접근

    • visit 배열에서, 방문하지 않은 node에 대해, DFS를 적용한다. 
    •  생각보다 낮은 정답률, 오랜만에 보는 '방향 없는 그래프' 때문에 겁먹었지만, 어렵지 않은 문제였다. 

    코드

    import java.util.*;
    import java.io.*;
     
    public class Main {
        static int N, M;
        static int map[][];
        static int visit[];
     
        public static void DFS(int x) {
            for (int i = 1; i <= N; i++) {
                int next = i;
                if (map[x][next] == 1 && visit[next] == 0) {
                    visit[next] = 1;
                    DFS(next);
                }
            }
        }
     
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            StringTokenizer st = new StringTokenizer(br.readLine());
     
            N = Integer.parseInt(st.nextToken());
            M = Integer.parseInt(st.nextToken());
     
            map = new int[N + 1][N + 1];
            visit = new int[N + 1];
     
            for (int i = 0; i < M; i++) {
                st = new StringTokenizer(br.readLine());
                int x = Integer.parseInt(st.nextToken());
                int y = Integer.parseInt(st.nextToken());
                map[x][y] = 1;
                map[y][x] = 1;
            }
     
            int COUNT = 0;
            for (int i = 1; i <= N; i++) {
                if (visit[i] == 0) {
                    DFS(i);
                    COUNT++;
                }
            }
     
            bw.write(COUNT + "\n");
     
            bw.flush();
            br.close();
        }
     
    }
    728x90

    'Solve Algorithms > BFS, DFS' 카테고리의 다른 글

    11403 : 경로 찾기  (0) 2020.04.22
    1012 : 유기농 배추  (0) 2020.04.19
    2468 : 안전 영역  (0) 2020.04.17
    1697 : 숨바꼭질  (0) 2020.04.17
    7576 : 토마토  (0) 2020.04.16

    댓글

kxmjhwn@gmail.com