2667 문제 링크
https://www.acmicpc.net/problem/2667
문제 설명

입출력

코드
< DFS >
|
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import java.io.*;
import java.util.*;
public class Main {
static int N;
static int[][] arr;
static boolean[][] visit;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
visit = new boolean[N][N];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < N; j++) {
arr[i][j] = input.charAt(j) - '0';
}
}
int totalCount = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 1 && !visit[i][j]) {
totalCount++;
int complexCount = dfs(i, j);
result.add(complexCount);
}
}
}
Collections.sort(result);
bw.write(String.valueOf(totalCount) + "\n");
for (int i : result) {
bw.write(String.valueOf(i) + "\n");
}
bw.flush();
}
private static int dfs(int x, int y) {
visit[x][y] = true;
int count = 1;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < N && ny < N) {
if (arr[nx][ny] == 1 && !visit[nx][ny]) {
count += dfs(nx, ny);
}
}
}
return count;
}
}
|
cs |
< BFS >
|
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
import java.io.*;
import java.util.*;
public class Main {
static int N;
static int[][] arr;
static boolean[][] visit;
static int[] dx = {0, 0, -1, 1};
static int[] dy = {1, -1, 0, 0};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
visit = new boolean[N][N];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < N; j++) {
arr[i][j] = input.charAt(j) - '0';
}
}
int totalCount = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 1 && !visit[i][j]) {
totalCount++;
int complexCount = bfs(i, j);
result.add(complexCount);
}
}
}
Collections.sort(result);
bw.write(String.valueOf(totalCount) + "\n");
for (int i : result) {
bw.write(String.valueOf(i) + "\n");
}
bw.flush();
}
private static int bfs(int x, int y) {
visit[x][y] = true;
int count = 1;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] {x,y});
while (!queue.isEmpty()) {
int[] current = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = current[0] + dx[i];
int ny = current[1] + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < N) {
if (arr[nx][ny] == 1 && !visit[nx][ny]) {
queue.offer(new int[] {nx, ny});
visit[nx][ny] = true;
count++;
}
}
}
}
return count;
}
}
|
cs |
알고리즘 설명
해당 문제는 dfs와 bfs 개념과 원리를 알고 있다면, 크게 어려울 것 없는 문제라고 생각합니다. 단지, 다음 배열로 넘어가기 위한 조건은 잘 설정하는 것이 중요합니다. dfs는 스택, bfs는 큐의 자료구조에 기반하기 때문에, dfs는 재귀함수 호출 / bfs는 반복문 이라는 것을 제외하면 큰 틀은 동일합니다. 시작하는 위치로부터 상,하,좌,우 이동 가능한 범위를 잘 설정하고, 다음 이동할 좌표값을 잘 설정해주고, dfs탐색 또는 bfs 탐색에 기반하여 해당 위치에서 더 이상 내려갈 노드가 없을 때, 함수를 종료하는 방식의 접근이 필요합니다.
탐색 알고리즘은 역시 dfs와 bfs가 가장 간단한 것 같습니다. 이진 탐색, 트리 탐색 등등 할 일이 태산이네요...

코드 해석
이중 for문을 사용해 2차원 배열 내 모든 원소 탐색.
• 원소의 숫자가 1이고 방문하지 않은 곳을 발견하면, DFS로 연결된 원소들을 모두 탐색하고, 단지의 크기를 계산.
• 각 단지의 크기를 리스트에 저장한 후, 최종적으로 단지 수와 각 단지 크기를 오름차순으로 출력.
'알고리즘 > 백준' 카테고리의 다른 글
| 백준 1012 유기농 배추 - JAVA (1) | 2025.02.05 |
|---|---|
| 백준 1920 수 찾기 - JAVA (1) | 2025.02.04 |
| 백준 10844 쉬운 계단 수 - JAVA (0) | 2025.02.02 |
| 백준 2579 계단 오르기 - JAVA (0) | 2025.02.01 |
| 백준 1932 정수 삼각형 - JAVA (0) | 2025.01.31 |
