[BOJ] 2667. 단지번호붙이기

동스토리 ㅣ 2020. 10. 22. 22:58

반응형

문제

www.acmicpc.net/problem/2667

 

2667번: 단지번호붙이기

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

www.acmicpc.net


해설

DFS 문제 풀이


코드

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

int map[26][26];
int visit[26][26];
int n, cnt;
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };

vector<int> q;

void dfs(int x, int y) {
	cnt++;
	visit[x][y] = true;

	for (int i = 0; i < 4; i++) {
		int nx = x + dx[i];
		int ny = y + dy[i];
		if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
		if (map[nx][ny] == 1 && visit[nx][ny] == false) {
			dfs(nx, ny);
		}
	}
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);

	cin >> n;

	for (int i = 0; i < n; i++) {
		string temp;
		cin >> temp;
		for (int j = 0; j < n; j++)	map[i][j] = temp[j] - '0';
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] == 1 && visit[i][j] == false) {
				cnt = 0;
				dfs(i, j);
				q.push_back(cnt);
			}
		}
	}

	sort(q.begin(), q.end());

	cout << q.size() << '\n';

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

	return 0;

}

 

 

 

반응형

'Development > Algorithm' 카테고리의 다른 글

[BOJ] 11724. 연결 요소의 개수  (0) 2020.10.27
[BOJ] 10799. 쇠막대기  (0) 2020.10.27
[BOJ] 9012. 괄호  (0) 2020.10.18
[BOJ] 11279. 최대 힙  (0) 2020.10.18
[BOJ] 1927. 최소 힙  (0) 2020.10.18