본문 바로가기
algorithm

[백준/c++][2667]단지번호붙이기

by blogsy 2019. 10. 11.

문제

 

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

 

입력

 

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

 

출력

 

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

 

코드

dfs

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

int n;
int a[30][30];
int map[30][30];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int ans[25*25];

void dfs(int x, int y, int count) {
	map[x][y] = count;
	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) {
			if (a[nx][ny] == 1 && map[nx][ny] == 0) {
				dfs(nx, ny, count);
			}
		}
	}
}

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%1d", &a[i][j]);
		}
	}

	int count = 0;

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (a[i][j] == 1 && map[i][j] == 0) {
				dfs(i, j, ++count);
			}
		}
	}

	printf("%d\n", count);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			ans[map[i][j]]++;
		}
	}

	sort(ans + 1, ans + count + 1);
	for (int i = 1; i <=count; i++) {
		printf("%d\n", ans[i]);
	}
	
	return 0;
}

bfs

#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;

int n;
int a[30][30];
int map[30][30];
int ans[25*25];

int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };

void bfs(int x, int y, int count) {
	queue<pair<int, int>> q;
	q.push(make_pair(x, y));
	map[x][y] = count;
	while (!q.empty()) {
		x = q.front().first;
		y = q.front().second;
		q.pop();
		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) {
				if (a[nx][ny] == 1 && map[nx][ny] == 0) {
					q.push(make_pair(nx, ny));
					map[nx][ny] = count;
				}
			}
		}
	}
}


int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++){
			scanf("%1d", &a[i][j]);
		}
	}

	int count = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (a[i][j] == 1 && map[i][j] == 0) {
				bfs(i, j, ++count);
			}
		}
	}
	printf("%d\n", count);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			ans[map[i][j]]++;
		}
	}

	sort(ans + 1, ans + count + 1);
	for (int i = 1; i <= count; i++) {
		printf("%d\n", ans[i]);

	}

	return 0;
}

메모

 

한 문자씩 입력받기

scanf("%1d", &a[i][j]);

'algorithm' 카테고리의 다른 글

[백준/c++][7576] 토마토  (0) 2019.10.14
[백준/c++][2178]미로 탐색  (0) 2019.10.14
[백준/c++][1707]이분 그래프  (0) 2019.10.11
[백준/c++][11724] 연결 요소의 개수  (0) 2019.10.10
[백준/c++][1182] 부분수열의 합  (0) 2019.10.04

댓글