반응형
-문제
문제 조건 제대로 읽기! 출력결과(단지내 집의 수)를 오름차순으로 정렬해서 출력해야한다!
-코드
#include<stdio.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int map[25][25];
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%1d", &map[i][j]);
// 붙어있는 수
}
}
queue<pair<int,int> > q;
int cnt = 0;
vector<int> res;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (map[i][j] == 1)
{
q.push({i,j});
map[i][j] = 0;
cnt = 1;
while (!q.empty())
{
pair<int, int> tmp = q.front();
q.pop();
for (int k = 0; k < 4; k++)
{
int xx = tmp.first + dx[k];
int yy = tmp.second + dy[k];
if (xx < 0 || yy < 0 || xx >= n || yy >= n) continue;
if (map[xx][yy] == 1)
{
q.push({ xx,yy });
map[xx][yy] = 0;
cnt++;
}
}
}
res.push_back(cnt);
}
}
}
if(res.size() == 0) printf("%d\n", 0);
else printf("%d\n", res.size());
sort(res.begin(), res.end());
for (int i = 0; i < res.size(); i++)
{
printf("%d\n", res[i]);
}
return 0;
}
반응형
'이론 > 코딩테스트' 카테고리의 다른 글
[백준] 2805번 나무자르기 (이분탐색) (0) | 2022.07.30 |
---|---|
[백준] 1920번 수 찾기 (이분탐색) (0) | 2022.07.30 |
[백준] 2178번 미로 탐색 (BFS) (0) | 2022.07.30 |
[백준] 1697번 숨바꼭질 (BFS) (0) | 2022.07.30 |
[백준] 2467번 용액 (투포인터 알고리즘) (0) | 2022.07.30 |