DFS, BFS 문제입니다.
1은 사람이 살고 있는 집입니다.
1과 인접해있는 곳에 1이 있으면 그곳들은 하나의 단지입니다.
이 때 몇개의 단지가 있고 단지마다 몇명이 살고 있는지 찾는 문제입니다.
먼저 입력받은 숫자들이 붙어있으므로
string으로 받아서 하나씩 잘라서 배열에 넣어주었습니다.
그리고 각 위치에서 마다 DFS를 실행하여 1이면 0으로 바꿔주면서
주변이 1인곳들을 전부 검색하고 그 수만큼 group배열에 +1씩 해줍니다.
한 단지의 인원을 다 구한경우 ++c를 해주므로써
다음 단지의 배열 위치를 지정할 수 있습니다.
모든 작업이 끝난 후 배열을 솔팅해주고 출력합니다.
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int map[30][30];
int group[1000];
int moveX[4] = { 0, 1, 0, -1 };
int moveY[4] = { 1, 0, -1, 0 };
void DFS(int a, int b, int count)
{
if (map[a][b] == 1) {
map[a][b] = 0;
for (int i = 0; i < 4; ++i) {
int x = a + moveX[i];
int y = b + moveY[i];
DFS(x, y, count);
}
++group[count];
}
}
int main(int argc, char *argv[])
{
memset(map, 0, sizeof(map));
memset(group, 0, sizeof(group));
int n;
string inputNum;
int c = 0;
int groupCount = 0;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> inputNum;
for (int j = 1; j <= n; ++j) {
map[i][j] = (inputNum[j - 1] - '0');
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
DFS(i, j, c);
if (group[c] != 0) {
++c;
}
}
}
for (int i = 0; i < 1000; ++i) {
if (group[i] == 0) {
groupCount = i;
break;
}
}
sort(group, group + groupCount);
cout << groupCount << endl;
for (int i = 0; i < groupCount; ++i) {
cout << group[i] << endl;
}
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 1237번 정ㅋ벅ㅋ (0) | 2019.08.03 |
---|---|
[C++] 백준 1012번 유기농 배추 (0) | 2019.07.30 |
[C++] 백준 11060번 점프 점프 (2) | 2019.07.18 |
[C++] 백준 1495번 기타리스트 (0) | 2019.07.16 |
[C++] 백준 2302번 극장 좌석 (0) | 2019.07.16 |