[백준] 2667번 단지번호붙이기 C++

semi·2022년 10월 5일
0

coding test

목록 보기
51/57

https://www.acmicpc.net/problem/2667

#include <iostream>
#include <string>
#include <queue>

using namespace std;

int N;
int house[26][26] = { 0, };
int visited[26][26] = { 0, };
int direct[4][2] = { {0, 1}, {1,0}, {-1, 0}, {0, -1} };
queue<pair<int, int>> q;
priority_queue<int> pq;
int BFS()
{
	int nx, ny, cnt = 1;
	pair<int, int> cur;
	while (!q.empty())
	{
		cur = q.front();
		q.pop();
		
		for (int i = 0; i < 4; i++)
		{
			nx = cur.first + direct[i][0]; // j
			ny = cur.second + direct[i][1]; //i
			if (nx >= 0 && nx < N && ny >= 0 && ny < N && house[ny][nx] == 1 && visited[ny][nx] == 0)
			{
				visited[ny][nx] = 1;
				q.push({ nx, ny });
				cnt++;
			}
		}
	}
	return cnt;
}

int main(void)
{
	int num_houses = 0;
	cin >> N;
	for (int i = 0; i < N; i++)
	{
		string str;
		cin >> str;
		for (int j = 0; j < N; j++)
		{
			house[i][j] = str[j] - '0';
		}
	}
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (visited[i][j] == 0 && house[i][j] == 1)
			{
				num_houses++;
				visited[i][j] = 1;
				q.push({ j, i });
				pq.push(-1 * BFS());
			}
		}
	}
	cout << num_houses << "\n";
	while (!pq.empty())
	{
		cout << -1 * pq.top() << "\n";
		pq.pop();
	}
	return 0;
}

0개의 댓글