알고리즘
[백준/BOJ] Bronze2 - 11724번 연결 요소의 개수 (JAVA)
전감자(◔◡◔)
2023. 4. 20. 00:02
문제
방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.
출력
첫째 줄에 연결 요소의 개수를 출력한다.
풀이
깊이 우선 탐색(DFS)을 사용하는 기본 문제이다.
깊이 우선 탐색에 대한 개념을 배우고 바로 풀어본 문제라 푸는데 시간이 오래걸렸다.
강의에선 스택을 사용하여 구현하였는데 재귀로 푸는게 더 일반적이라고 해서 재귀로 풀어보았다
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static int n,m;
static boolean[] visited; //방문 했는지 안했는지 구분
static ArrayList<Integer>[] adjList; //인접리스트
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); //노드 개수
m = sc.nextInt(); //간선 개수
// 인접리스트 초기화
adjList = new ArrayList[n+1];
for(int i = 1; i <= n; i++) {
adjList[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
adjList[u].add(v);
adjList[v].add(u);
}
visited = new boolean[n+1];
int cnt = 0;
// 각 노드에 대해서 dfs
for(int i = 1; i <= n; i++) {
if(visited[i] != true) {
cnt++;
dfs(i);
}
}
System.out.println(cnt);
}
private static void dfs(int node) {
visited[node] = true; //방문여부를 true로 바꿔줌
for( Integer adj_node : adjList[node]) {
//방문 노드에 대해 인접한 노드를 꺼내옴
if(visited[adj_node] != true) {
//인접 노드에 방문안했으면 dfs
dfs(adj_node);
}
}
}
}