Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
Tags
- 백트렉킹
- 너비우선탐색
- Java
- 1174
- 39080
- 백트랙킹
- openssl
- 코딩테스트
- 부분 수열의 합
- BOJ
- ElementTree
- 백준
- 재귀
- DP
- 순열장난
- 백트래킹
- 문서자동화
- dfs
- 그래프
- 입실 퇴실
- 좋은 수열
- 프로그래머스
- 위클리 챌린지
- 복서 정렬하기
- 10597
- 위클리 6주차
- 완전 탐색
- 줄어드는 숫자
- BFS
- 몯느 순열
Archives
개발자-H 입니다.
BOJ - 연결 요소의 개수 (11724) 본문
https://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
- 그래프를 탐색하며 연결 요소를 구하는 문제이다.
- DFS 탐색 횟수를 카운팅하여 연결 요소를 개수를 구했다.
- 그래프 기본 문제 유형인듯
package baekjoon;
import java.lang.*;
import java.util.*;
public class Main {
public static final Scanner scanner = new Scanner(System.in);
public static final int NOT_VISITED = -1;
public static void main(String[] args) throws Exception {
int V = scanner.nextInt();
int M = scanner.nextInt();
ArrayList<Integer>[] adj = new ArrayList[V + 1];
int[] visited = new int[V + 1];
Arrays.fill(visited, NOT_VISITED);
for (int i = 0; i <= V; i += 1) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < M; i += 1) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adj[u].add(v);
adj[v].add(u);
}
Integer connected = 0;
for (int i = 1; i <= V; i++) {
if (visited[i] == NOT_VISITED) {
connected += 1;
dfsRecursive(i, connected, visited, adj);
}
}
System.out.println(connected);
}
private static void dfsRecursive(int currentNode, Integer connected, int[] visited, ArrayList<Integer>[] adj) {
visited[currentNode] = connected;
for (int i = 0; i < adj[currentNode].size(); i++) {
Integer next = adj[currentNode].get(i);
if (visited[next] == NOT_VISITED) {
dfsRecursive(next, connected, visited, adj);
}
}
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
구름 - 길찾기 (다이아몬드) (0) | 2021.08.08 |
---|---|
LeetCode - FloodFile (0) | 2021.08.07 |
BOJ - 섬의 개수 (4963) (0) | 2021.08.07 |
BOJ - 단지번호붙이기 (2667) (0) | 2021.08.07 |
프로그래머스 - 가장 먼 노드 (0) | 2021.08.04 |
Comments