11724

qkrrnjswo·2023년 7월 21일
0

백준, 프로그래머스

목록 보기
39/53

1. 연결 요소의 개수

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

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


2. 나만의 문제 해결

너비 우선 탐색을 이용해서 품
  

3. code


public class Main {
	static ArrayList<Integer>[] edges;
	static boolean[] visit;
	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 edge = Integer.parseInt(st.nextToken());
		int count = 0;
		edges = new ArrayList[n+1];
		visit = new boolean[n+1];

		for (int i=1; i<=n; i++) {
			edges[i] = new ArrayList<Integer>();
		}


		for (int i = 0; i < edge; i++) {
			st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());
			edges[x].add(y);
			edges[y].add(x);
		}

		for (int i = 1; i <= n; i++) {
			if (!visit[i]) {
				BFS(i);
				count++;
			}
		}
		System.out.println(count);
	}

	static void BFS(int s) {
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(s);
		visit[s] = true;

		while (!queue.isEmpty()) {
			int now = queue.poll();
			for (int next : edges[now]) {
				if (visit[next]) continue;
				queue.offer(next);
				visit[next] = true;
			}
		}
	}
}

0개의 댓글