본문 바로가기

하루하나코딩

백준 2667번 : 단지번호붙이기 c++

코드

#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;

int N;
char map[26][26];
bool visited[26][26];
int ans = 0;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int a[1000];

bool compare(int a, int b){
	return a < b;
}

void dfs(int x, int y, int z){
	visited[x][y] = true;
	
	for(int k = 0; k < 4; k++){
		int next_x = x+dx[k];
		int next_y = y+dy[k];
		if(next_x >= 0 && next_y >=0 && next_x<=N && next_y <=N){
			if(visited[next_x][next_y] == false && map[next_x][next_y] == '1'){
			a[z]++;
			dfs(next_x, next_y, z);
			visited[next_x][next_y] = true;
			}
		}	
	}	
}


int main(){
	
	cin >> N;
	
	for(int i = 0; i < N; i++){
		memset(visited[i], false, sizeof(visited[i]));
	}
	
	memset(a, 0, sizeof(a));
	
	for(int i = 0; i < N; i++){
		for(int j = 0; j < N; j++){
			cin >> map[i][j];
		}
	}
	
	for(int i = 0; i < N; i++){
		for(int j = 0; j < N; j++){
			if(visited[i][j] == false && map[i][j] == '1'){
				dfs(i, j, ans);
				ans++;
			}
		}
	}
	
	cout << ans << endl;
	
	sort(a, a+ans, compare);
	
	for(int i = 0; i < ans; i++){
		cout << a[i] + 1  << endl;
	} 
	
	return 0;	
}

설명

그냥 dfs..돌리면 됩니다..

단지의 수가 25갠줄알고 안돼서 질문했는데,,

훨씬 많을 수 있겠네요.. 조심하세요!

'하루하나코딩' 카테고리의 다른 글

백준 2644번 : 촌수계산 c++  (0) 2022.12.31
백준 1874번 : 스택수열 c++  (0) 2022.12.31
백준 2606번 : 바이러스 c++  (0) 2022.12.29
백준 2178번 : 미로 탐색 c++  (0) 2022.12.28
백준 1260번 : DFS와 BFS c++  (0) 2022.12.27