Algorithm/Algorithms Practice
[BOJ/C++] 단지번호붙이기(2667번)
Patrick_
2022. 10. 19. 14:48
1. 개요
https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
1-1. 설명
아래 그림과 같이 정사각형 모양 지도가 있다. 집이 있는곳은 1, 없는 곳은 0으로 나타낸다. 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지 번호를 붙이려 한다. 아래 오른쪽 그림은 단지별로 번호를 붙인 것이다. 지도를 입력해 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성한다.
1-2. 제한 사항
- 첫 줄에 지도의 크기N이 주어지며, N은 5 이상 25 이하
- 이후 다음 줄부터 N개의 자료가 입력
2. 구현
2-1. 풀이
DFS를 통해 1인 부분은 모두 탐색하고, 개수를 저장하게끔 하였다.
2-2. 코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
int x;
int y;
};
int maps[25][25];
bool visited[25][25];
Node stack[25 * 25];
vector<int> result;
int dirX[4] = { -1, 1, 0, 0 };
int dirY[4] = { 0, 0, -1, 1 };
int N, numCnt;
void DFS(int i, int j) {
int top = -1, startX = i, startY = j;
stack[++top] = { startX, startY };
while (top != -1) { // stack을 모두 돌때 종료
Node cur = stack[top--];
if (visited[cur.x][cur.y]) continue; // 이미 방문한 노드라면
visited[cur.x][cur.y] = true;
if (maps[cur.x][cur.y] == 1) numCnt += 1; // 현재 위치가 1일 때
for (int i = 0; i < 4; i++) { // 4 방향으로 스택 저장
int nextX = cur.x + dirX[i];
int nextY = cur.y + dirY[i];
if (nextX >= 0 && nextX < N && nextY >= 0 && nextY < N) { // N 범위 안이고
if (maps[nextX][nextY] == 1 && !visited[nextX][nextY]) { // 방문하지 않은 1일때
stack[++top] = { nextX, nextY };
}
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
for (int i = 0; i < N; i++) {
string str;
int index = 0;
cin >> str;
for (char ch : str) {
maps[i][index++] = (int)ch - '0';
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (maps[i][j] == 1 && !visited[i][j]) {
numCnt = 0;
DFS(i, j);
result.push_back(numCnt);
}
}
}
sort(result.begin(), result.end());
cout << result.size() << "\n";
for (int num : result) cout << num << "\n";
return 0;
}