알고리즘 공부

백준 단지번호붙이기

컴퓨터과학 2023. 7. 7. 21:52

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

 

2667번: 단지번호붙이기

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

www.acmicpc.net

쉽네요~~~~

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

struct Point {
	int x, y;
};

void Prints(vector<vector<int>>maps, int n, int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j];
		}
		cout << endl;
	}
	cout << endl;
}

void Prints(vector<vector<bool>>maps, int n, int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j];
		}
		cout << endl;
	}
	cout << endl;
}

int main() {
	int n;
	cin >> n;
	vector<vector<int>>maps;
	vector<bool>tmpbVisited(n, false);
	vector<vector<bool>>bVisited(n, tmpbVisited);
	for (int i = 0; i < n; i++) {
		string tmp;
		vector<int>tmpMaps;
		cin >> tmp ;
		for (int j = 0; j < n; j++) {
			 int a= tmp[j]-'0';
			 tmpMaps.push_back(a);
			 if (a == 0) {
				 bVisited[i][j] = true;
			 }
		}
		maps.push_back(tmpMaps);
	}

	int drx[] = { 0,0,1,-1 };
	int dry[] = { 1,-1,0,0 };
	queue<Point>q;
	int gCount = 0;
	
	vector<int>citys;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
		
			int cityCount = 0;
			if (maps[i][j] == 1&&bVisited[i][j]==false) {
				
				bVisited[i][j] = true;
				Point p;
				p.y = i;
				p.x = j;
				q.push(p);
				
				gCount++;
				maps[i][j] = gCount;
				cityCount++;
				while (!q.empty()) {
					Point start = q.front();
					q.pop();

					for (int i = 0; i < 4; i++)
					{
						int tmpdrx = start.x + drx[i];
						int tmpdry = start.y + dry[i];
						
				        if (tmpdrx == -1 || tmpdry == -1 || tmpdry > n - 1 || tmpdrx > n - 1) {
							continue;
						}
						if (maps[tmpdry][tmpdrx] == 1 && bVisited[tmpdry][tmpdrx] == false) {
							
							Point tmpP;
							tmpP.x = tmpdrx;
							tmpP.y = tmpdry;
							
						
							q.push(tmpP);
							maps[tmpdry][tmpdrx] = gCount;
							bVisited[tmpdry][tmpdrx] = true;
							cityCount++;
							
						}

					}
				}
				citys.push_back(cityCount);
			}
		}
	}
	cout << gCount<<endl;
	if (citys.size() > 0) {
		sort(citys.begin(), citys.end());
	}
	for (int i = 0; i < citys.size(); i++) {
		cout<< citys[i] << endl;
	}
	return 0;
}