a[집 갯수] = 단지 갯수
for(int i = 0; i < n*n + 1; i++){
for(int j = 0; j < a[i]; j++){
cout << i << "\n";
}
}
18.2.7
소스코드 수정 - num이 필요없잖아.. 벡터를 쓰는데
dfs만 수정함
소스코드 : dfs
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n;
vector<int> house;
char map[25][25];
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, -1, 0, 1 };
int dfs(int row, int col){
map[row][col] = '0';
int ret = 1, nr, nc;
for (int i = 0; i < 4; i++){
nr = row + dx[i];
nc = col + dy[i];
if (0 <= nr && nr < n && 0 <= nc && nc < n && map[nr][nc] == '1')
ret += dfs(nr, nc);
}
return ret;
}
int main(void){
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> map[i][j];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (map[i][j] == '1')
house.push_back(dfs(i, j));
sort(house.begin(), house.end());
cout << house.size() << "\n";
for (int i = 0; i < house.size(); i++)
cout << house.at(i) << "\n";
return 0;
}
소스코드 : bfs
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int n, check[25][25];
char map[25][25];
vector<int> house;
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, -1, 0, 1 };
int main(void){
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> map[i][j];
queue<pair<int, int>> q;
int num = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
int cnt = 0;
if (!check[i][j] && map[i][j] == '1'){
q.push(make_pair(i, j));
check[i][j] = true;
num++; cnt++;
while (!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
int nx, ny;
for (int k = 0; k < 4; k++){
nx = x + dx[k];
ny = y + dy[k];
if (0 <= nx && nx < n && 0 <= ny && ny < n
&& !check[nx][ny] && map[nx][ny] == '1'){
check[nx][ny] = true;
cnt++;
q.push(make_pair(nx, ny));
}
}
}
house.push_back(cnt);
}
}
}
sort(house.begin(), house.end());
cout << num << "\n";
for (int i = 0; i < house.size(); i++)
cout << house.at(i) << "\n";
}
[출처 : BOJ, 문제에 대한 모든 권리는 BOJ(acmicpc.net, startlink)에 있음]