문제 링크: https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수
www.acmicpc.net
DFS
'1'로 이루어져 있는 component의 갯수와, 각 component마다 vertex의 갯수를 구해서 오름차순으로 sort하면 됨.
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
|
#include <bits/stdc++.h>
using namespace std;
int N, visited[26][26];
int dy[4] = {0, 0, -1, 1}, dx[4] = {-1, 1, 0, 0};
char arr[26][26];
vector<int> ans;
int dfs(int y, int x) {
visited[y][x] = 1;
int ret = 1;
for(int d = 0; d < 4; d++) {
int yy = y + dy[d], xx = x + dx[d];
if(yy >= 0 && xx >= 0 && yy < N && xx < N && arr[yy][xx] == '1' && !visited[yy][xx])
ret += dfs(yy, xx);
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N;
for(int i = 0; i < N; i++) for(int j = 0; j < N; j++)
cin >> arr[i][j];
for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) {
if(arr[i][j] == '1' && !visited[i][j])
ans.push_back(dfs(i, j));
}
sort(ans.begin(), ans.end());
int comp = ans.size();
cout << comp << '\n';
for(int i = 0; i < comp; i++)
cout << ans[i] << '\n';
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
'KOI > 초등부' 카테고리의 다른 글
백준 2309 일곱 난쟁이 (KOI 지역본선 2004 초등부 1번) (0) | 2020.03.21 |
---|