본문 바로가기
이론/코딩테스트

[백준] 2667번 단지번호붙이기 (BFS)

by 퇴근후개발 2022. 7. 30.
반응형

-문제

문제 조건 제대로 읽기! 출력결과(단지내 집의 수)를 오름차순으로 정렬해서 출력해야한다!

 

-코드

#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;
}
반응형