[백준 알고리즘]/[C++]
2667번 단지번호붙이기 | DFS | Baekjoon BOJ 백준 2667 C++ 코드, 해설, 풀이
말하는펭귄
2021. 1. 30. 10:47
728x90
반응형
이번 포스팅은 백준 2667번 단지번호붙이기입니다.
아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
기본 알고리즘
DFS 깊이우선탐색
참고
변수 설명
label: 단지 번호
v: 단지에 속하는 집 수 저장 벡터
house: 단지에 속하는 집 수
전체 코드
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
|
//백준2667 단지번호붙이기
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
const int MAX = 25;
int N;
int map[MAX][MAX] = { 0, };
bool visited[MAX][MAX] = { 0, };
int dy[] = { 0,0,1,-1 };
int dx[] = { 1,-1,0,0 };
int label = 1;
vector<int> v;
int house = 0;
void DFS(int y, int x) {
visited[y][x] = true;
map[y][x] = label;
house++;
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)
continue;
if (map[ny][nx] == 1 && visited[ny][nx] == 0) {
DFS(ny, nx);
}
}
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
string input;
cin >> input;
for (int j = 0; j < N; j++) {
map[i][j] = input.at(j) - '0';
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1 && visited[i][j] == 0) {
DFS(i, j);
label++;
v.push_back(house);
house = 0;
}
}
}
sort(v.begin(), v.end());
cout << label-1 << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
}
|
cs |
728x90
반응형