티스토리 뷰

PS/BOJ C++

2667번 - 단지번호붙이기

zpqmdh 2022. 1. 20. 01:25

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

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int N;
int Map[26][26];
bool isVisited[26][26] = { false };

int ans = 0; //총 단지수
int danji[25 * 25];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };


bool isPossible(int row, int col)
{
	if (row < 0 || row >= N || col < 0 || col >= N)
		return false;
	return true;
}
void bfs(int row, int col)
{	
	queue<pair<int, int>> q; // bfs 탐색을 위한 queue
	q.push(make_pair(row, col));
	isVisited[row][col] = true;
	danji[ans]++;
	while (!q.empty())
	{
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int nx = x + dx[i];
			int ny = y + dy[i];
			//이동 가능하고 집이 있고 방문하지 않았을 때
			if (true == isPossible(nx, ny) && 1 == Map[nx][ny] && false == isVisited[nx][ny])
			{
				q.push(make_pair(nx, ny));
				isVisited[nx][ny] = true;
				danji[ans]++;
			}
		}
	}
}
int main()
{
	cin >> N;
	for (int i = 0; i < N; i++)
	{
		string str;
		cin >> str;
		for (int j = 0; j < N; j++)
			Map[i][j] = str[j] - '0';
	}

	
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			//집이 있고, 방문하지 않은 집일 때
			if (1 == Map[i][j] && false == isVisited[i][j] )
			{
				ans++; //단지의 개수 증가
				bfs(i, j); //bfs 실시
			}
		}
	}
	sort(danji+1, danji + ans+1); //오름차순 정렬

	cout << ans << '\n';
	for (int i = 1; i <= ans; i++)
		cout << danji[i] << '\n';
	return 0;
}

'PS > BOJ C++' 카테고리의 다른 글

2636번 - 치즈  (0) 2022.01.25
1013번 - Contact  (0) 2022.01.22
2920번 - 음계  (0) 2022.01.15
2178번 - 미로 탐색  (0) 2022.01.11
14502번 - 연구소  (0) 2022.01.09
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함