본문 바로가기

알고리즘/BFS

백준 2667 단지 번호


#include 
#include 
#include 
using namespace std;

typedef struct {
	int position_x;
	int position_y;
}apartment;

int Map[25][25];
bool visit[25][25];
int N;
queue q;
priority_queue<int,vector, greater> pq;
int dirx[4] = {0,0,1,-1};
int diry[4] = {-1,1,0,0};


void Input() {
	scanf("%d", &N);
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			scanf("%1d", &Map[i][j]);
		}
	}
}

void Calc() {
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			if (visit[i][j]) continue;
			visit[i][j] = true;
			if (Map[i][j] == 0) continue;
			q.push({ j,i });
			int count = 1;
			while (!q.empty()) {
				int po_x = q.front().position_x;
				int po_y = q.front().position_y;
				q.pop();
				for (int k = 0; k < 4; k++) {
					int next_x = po_x + dirx[k];
					int next_y = po_y + diry[k];
					if (next_x < 0 || next_y < 0 || next_x >= N || next_y >= N) continue;
					if (visit[next_y][next_x]) continue;
					if (Map[next_y][next_x] == 1) {
						/*printf("next_x : %d , next_y : %d",next_x, next_y );*/
						count++;
						visit[next_y][next_x] = true;
						q.push({ next_x, next_y });
					}
				}
			}
			if (count > 0) pq.push(count);
		}
	}
	int length = pq.size();
	printf("%d\n", length);
	for (int i = 0; i < length; i++) {
		printf("%d\n", pq.top());
		pq.pop();
	}
}

void Solve() {
	Input();
	Calc();
}

int main(void) {
	Solve();
	return 0;
}

후기 : 처음에 에러가 나길래 왜 그런가 파악 하기 위해 최악의 케이스를 적용시켜봤더니 문제는 1개의 아파트만 존재할때 무시하고 건너간다는 것이였다. 그러므로 1개의 아파트만 존재하는 단지가 있으므로 count>0으로 체크해주었더니 해결할수 있었다. 

 

 

 

 

 

 

 

 

 

 

 

 

'알고리즘 > BFS' 카테고리의 다른 글

백준 17142 연구소 3  (0) 2019.05.18
백준 11403 경로 찾기  (0) 2019.04.23
백준 1012번 유기농배추.  (0) 2019.04.23
백준 7576 토마토  (0) 2019.04.22