백준온라인저지
단지번호붙이기 - 2667번 풀이
문제 링크 ↓↓↓
https://www.acmicpc.net/problem/2667
N과 N*N형태의 인풋이 주어지고,
연결되어 있는 '1'들의 그룹을 찾아 넘버링 한 뒤,
총 갯수와 그룹넘버를 출력하는 문제
분류는 BFS와 DFS로 되어있으며,
둘 중 아무거나 사용하여도 문제 없음
이제 막 BFS와 DFS를 배웠다면, 연습하기에 나쁘지않은 것 같다.
나의 경우, 0,0부터 탐색해서 1이 존재하면 그 지점부터
탐색을 시작하는데, 방문여부 체크는 필수적으로 해주어야 한다
놀라운 점은 이 문제가 96년 정보올림피아드 초등부 1번이었다는 사실이다..
소스코드 ↓↓↓
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
69
70
71
72
73
74
|
#include<stdio.h>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
int cnt;
void findPot(int map[26][26], int i, int j,int n) {
if (i - 1 >= 0 && map[i - 1][j] != 0) {
map[i - 1][j] = 0;
cnt++;
findPot(map,i - 1, j, n);
}
if (i + 1 < n && map[i + 1][j] != 0) {
map[i + 1][j] = 0;
cnt++;
findPot(map, i + 1, j, n);
}
if (j - 1 >= 0 && map[i][j - 1] != 0) {
map[i][j - 1] = 0;
cnt++;
findPot(map, i, j - 1, n);
}
if (j + 1 < n && map[i][j + 1] != 0) {
map[i][j + 1] = 0;
cnt++;
findPot(map, i, j + 1, n);
}
}
int main() {
int totPot = 0;
int n;
char inputC;
int map[26][26] = { 0, };
vector<int> vec;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%c", &inputC);
if (inputC != '\n') {
map[i][j] = atoi(&inputC);
}
else
j--;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] != 0) {
map[i][j] = 0;
cnt++;
findPot(map, i, j, n);
vec.push_back(cnt);
totPot++;
cnt = 0;
}
}
}
sort(vec.begin(), vec.end());
printf("%d\n", totPot);
for(int i =0;i<(int)vec.size();i++){
printf("%d\n", vec[i]);
}
return 0;
}
|
cs |
댓글