Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 11724. 연결 요소의 개수 본문

acmicpc

[BAEKJOON] 11724. 연결 요소의 개수

코드와이 2021. 3. 4. 22:30

 

bfs

문제링크

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

 

package acmicpc.Silver2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class 연결요소의_갯수 {
	
	static int[][] map;
	static boolean[] visited;
	static int n, m;
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		map = new int[n+1][n+1];
		
		for(int i = 0 ; i < m ; i++) {
			st = new StringTokenizer(br.readLine());
			int r = Integer.parseInt(st.nextToken());
			int c = Integer.parseInt(st.nextToken());
			map[r][c] = 1;
			map[c][r] = 1;
		}
		visited = new boolean[n+1];
		visited[0] = true;
		int ans = 0;
		for(int i = 1 ; i <= n ; i++) {
			if(visited[i]) continue;
			ans += 1;
			func(i);
		}
		System.out.println(ans);
	}
	
	public static void func(int idx) {
		Queue<Integer> queue = new LinkedList<Integer>();
		
		queue.add(idx);
		while(!queue.isEmpty()) {
			int q = queue.poll();
			visited[q] = true;
			for(int i = 1 ; i <= n ; i++) {
				if(!visited[i] && map[i][q] == 1) {
					visited[i] = true;
					queue.add(i);
				}
			}
		}
	}
}