본문 바로가기

백준/C++

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

728x90

 

문제 2667번

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

 

map에 넣을 입력값을 받을 때 공백이 없기 때문에 문자열로 한줄씩 받아줘야하는데 그냥 int로 받아버렸다. 그래서 한참 고민했다...

 

게다가 문자 하나하나를 비교하여 '1'이면 정수 1을 map에 넣어주고 '0'이면 0을 넣어줘야한다. 그런데 '1'인지 확인할 때 문자 표시인 작은따옴표를 쓰지 않아 숫자로 인식했다...

 

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

int map[26][26];
bool visited[26][26];
vector<int> result;
int n;
int x[4] = { 0,0,-1,1 };
int y[4] = { 1,-1,0,0 };

void bfs(int a, int b) {
	int cnt = 0;
	queue<pair<int, int>> q;
	q.push(make_pair(a, b));
	visited[a][b] = true;
	cnt++;
	while (!q.empty()) {
		int x_first = q.front().first;
		int y_first = q.front().second;
		q.pop();
		for (int i = 0; i < 4; i++) {
			int x_next = x_first + x[i];
			int y_next = y_first + y[i];
			if (map[x_next][y_next] == 1 && visited[x_next][y_next] != true &&
				0 <= x_next && x_next < n && 0 <= y_next && y_next < n) {
				q.push(make_pair(x_next, y_next));
				visited[x_next][y_next] = true;
				cnt++;
			}
		}
	}
	result.push_back(cnt);
}

int main() {
	string str;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> str;
		for (int j = 0; j < str.length(); j++) {
			if (str[j] == '1') {
				map[i][j] = 1;
			}
			else {
				map[i][j] = 0;
			}
		}
	}
	
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] == 1 && visited[i][j] != true) {
				bfs(i, j);
			}
		}
	}
	sort(result.begin(), result.end());

	cout << result.size() << '\n';
	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << '\n';
	}

	return 0;
}

 

 

 

728x90