🙇‍♀️[Silver I] 단지번호붙이기 - 2667

문제 링크

성능 요약

메모리: 2036 KB, 시간: 0 ms

분류

너비 우선 탐색, 깊이 우선 탐색, 그래프 이론, 그래프 탐색

제출 일자

2023년 12월 30일 15:02:44

문제 설명

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

입력

첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

출력

첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

🚀풀이

BFS문제였다.

전체 지도를 탐색하면서 0이 아니면서 발견한 지역이 아니라면 BFS를 돌린다.

BFS를 돌릴 때마다 cnt가 증가하며 cnt에 따라서 단지 번호가 부여된다.

int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
void BFS(int y, int x)
{
	int ny, nx;
	queue<pair<int, int>> q;
	q.push({ y, x });
	discovered[y][x] = 1;

	while (q.empty() == false)
	{
		pair<int, int> here = q.front();
		q.pop();
		res[cnt]++; // 여기서 해당 단지의 건물이 몇개인지 카운트 해줌.

		for (int i = 0; i < 4; ++i)
		{
			ny = here.first + dy[i];
			nx = here.second + dx[i];

			if (ny < 1 || nx < 1 || ny > n || nx > n)
				continue;
			if (board[ny][nx] == 0)
				continue;
			if (discovered[ny][nx] == 1)
				continue;

			discovered[ny][nx] = 1;
			q.push({ ny, nx });
		}
	}
}
void solve()
{
	setting();

	for (int y = 1; y <= n; ++y)
	{
		for (int x = 1; x <= n; ++x)
		{
            // 보드에서 1의 값을 가지면서 발견을 안했다면?
			if (board[y][x] == 1 && discovered[y][x] == 0)
			{
				BFS(y, x);
				//cout << endl;
				cnt++;
			}
		}
	}

    // 끝까지 정렬하면 0으로 도배됨.
	sort(res.begin(), res.begin() + cnt);

	cout << cnt << '\n';

	for (int i = 0; i < cnt; ++i)
	{
		cout << res[i] << '\n';
	}
}

🚀전체 코드

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

int n, cnt = 0;
int board[27][27];
int discovered[27][27];
vector<int> res;
void setting()
{
	cin >> n;
	res = vector<int>(n * n);

	string str;
	for (int y = 1; y <= n; ++y)
	{
		cin >> str;
		for (int x = 1; x <= n; ++x)
		{
			board[y][x] = str[x - 1] - '0';
		}
	}
}

int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
void BFS(int y, int x)
{
	int ny, nx;
	queue<pair<int, int>> q;
	q.push({ y, x });
	discovered[y][x] = 1;

	while (q.empty() == false)
	{
		pair<int, int> here = q.front();
		q.pop();
		//cout << cnt << "단지 : " << here.first << " : " << here.second << endl;
		res[cnt]++;

		for (int i = 0; i < 4; ++i)
		{
			ny = here.first + dy[i];
			nx = here.second + dx[i];

			if (ny < 1 || nx < 1 || ny > n || nx > n)
				continue;
			if (board[ny][nx] == 0)
				continue;
			if (discovered[ny][nx] == 1)
				continue;

			discovered[ny][nx] = 1;
			q.push({ ny, nx });
		}
	}
}

void solve()
{
	setting();

	for (int y = 1; y <= n; ++y)
	{
		for (int x = 1; x <= n; ++x)
		{
			if (board[y][x] == 1 && discovered[y][x] == 0)
			{
				BFS(y, x);
				//cout << endl;
				cnt++;
			}
		}
	}

	sort(res.begin(), res.begin() + cnt);

	cout << cnt << '\n';

	for (int i = 0; i < cnt; ++i)
	{
		cout << res[i] << '\n';
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	freopen("input.txt", "rt", stdin);

	solve();

	return 0;
}