백준 11724 연결 요소의 개수 (Java)

김주현·2020년 1월 6일
0

풀이
백준 DFS/BFS 문제와 거의 비슷한 문제로 DFS 또는 BFS를 사용하여 간선으로 연결되어있는 정점들의 집합의 갯수를 찾는 문제.
정점의 개수 만큼 for을 돌며 visited에 기록이 되어있지 않으면 DFS/BFS함수에 들어가서 해당 연결 되어있는 간선들을 찾고 연결 요소들을 모두 찾고 나올 시 count해주는 방식으로 구현.

소스코드

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    
    public class ConnectedComponent {
    
        static ArrayList<ArrayList<Integer>> map = new ArrayList<>();
        static boolean visited[];
        static int count = 0;
    
        public static void main(String args[]) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine());
    
            int N = Integer.parseInt(st.nextToken());
            int M = Integer.parseInt(st.nextToken());
    
            for(int i = 0; i<=N; i++){
                map.add(new ArrayList<>());
            }
    
            visited = new boolean[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.get(x).add(y);
                map.get(y).add(x);
            }
    
            for(int i = 1; i <= N; i++){
                if(!visited[i]){
                    dfs(i);
                    count ++;
                }
            }
    
            System.out.println(count);
    
        }
    
        public static void dfs(int v){
            visited[v] = true;
    
            for(int value : map.get(v)){
                if(!visited[value]){
                    dfs(value);
                }
            }
        }
    }
profile
Hello World

0개의 댓글