백준|11724번|연결 요소의 개수

JSK·2022년 7월 31일
0

자바 PS풀이

목록 보기
12/51

문제설명
그래프의 정점과 간선들을 입력받고 몇개의 연결 요소로 이루어져있는지 출력하는 문제입니다.

작동 순서
1. 그래프의 정점과 간선들의 개수를 입력받습니다.
2. 그래프의 간선들을 입력받고 각 정점의 연결리스트에 삽입해줍니다.
3. 정점들중 하나를 선택해서 너비 우선 탐색을 하고 연결요소를 세는 변수 count에 1을 더해줍니다.
4. 만약 탐색을 시작한 원소에 이어진 원소들이 있을 경우 해당 원소들을 방문처리 해줍니다.
5. 탐색이 끝났으면 방문처리가 되어있지 않은 정점들중 하나를 선택해서 너비 우선 탐색을 하고 연결요소를 세는 변수 count에 1을 더해줍니다.
6. 위 과정을 방문처리가 되자 않은 원소가 없을 때까지 반복합니다.

소스코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class 백준_11724번_연결요소의개수 {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String[] input=br.readLine().split(" ");
        int N=Integer.parseInt(input[0]), M=Integer.parseInt(input[1]), now=0, visit_count=0, count=0;
        LinkedList<Integer>[] comp=new LinkedList[N+1];
        Queue<Integer> connect=new LinkedList<Integer>();
        boolean[] visited=new boolean[N+1];
        visited[0]=true;

        for(int i=0;i<comp.length;i++) comp[i]=new LinkedList<Integer>();
        for(int i=0;i<M;i++){
            input=br.readLine().split(" ");
            comp[Integer.parseInt(input[0])].add(Integer.parseInt(input[1]));
            comp[Integer.parseInt(input[1])].add(Integer.parseInt(input[0]));
        }
        for (int i=1;i<comp.length;i++) Collections.sort(comp[i]);

        while(visit_count<N) {
            for(int i=1;i<N+1;i++){
                if(visited[i]==false) {
                    now=i;
                    break;
                }
            }
            visited[now] = true;
            visit_count++;
            count++;
            connect.add(now);
            while (connect.size() > 0) {
                now = connect.poll();
                while (comp[now].size() > 0) {
                    int next = comp[now].poll();
                    if (!visited[next]) {
                        visited[next] = true;
                        visit_count++;
                        connect.add(next);
                    }
                }
            }
        }
        System.out.print(count);
    }
}

후기
저는 단순하게 너비우선탐색이 시작되는 횟수를 세었는데 다른 분들의 풀이를 보니 유니온파인드라는 기법을 이용한 코드들이 보였습니다. 알고리즘은 배울게 너무나도 많고 아는것이 없구나라고 느낀것 같습니다.

profile
학사지만 AI하고 싶어요...

0개의 댓글