지우너
[코드트리] 마을 구분하기 C++ DFS 본문
문제
https://www.codetree.ai/missions/2/problems/seperate-village?&utm_source=clipboard&utm_medium=text
코드트리 | 코딩테스트 준비를 위한 알고리즘 정석
국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.
www.codetree.ai
풀이
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX_N 26
using namespace std;
int n, sum;
int arr[MAX_N][MAX_N];
bool visited[MAX_N][MAX_N]={false, };
vector<int> population;
bool InRange(int x, int y){
return x>=0 && x<n && y>=0 && y<n;
}
bool CanGo(int x, int y){
// 범위를 벗어남
if(!InRange(x, y)) return false;
// 방문함 || 벽
if(visited[x][y] || arr[x][y]==0) return false;
return true;
}
void DFS(int x, int y){
// 상하좌우
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
visited[x][y]=true;
sum++;
for(int dir=0; dir<4; ++dir){
int nx=x+dx[dir], ny=y+dy[dir];
if(CanGo(nx, ny)){
DFS(nx, ny);
}
}
}
int main() {
// input
cin >> n;
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
cin >> arr[i][j];
}
}
// solution
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
// 방문함 || 벽
if(visited[i][j] || arr[i][j]==0) continue;
// sum 초기화
sum=0;
DFS(i, j);
population.push_back(sum);
}
}
sort(population.begin(), population.end());
// output
cout << population.size() << '\n';
for(size_t i=0; i<population.size(); ++i){
cout << population[i] << '\n';
}
return 0;
}
'Problem Solving' 카테고리의 다른 글
[코드트리] 자리 바꾸기2 C++ unordered_set (0) | 2024.08.01 |
---|---|
[코드트리] treemap 기본 C++ (0) | 2024.07.31 |
[코드트리] 둘 중 하나 잘 고르기 C++ (0) | 2024.07.17 |
[코드트리] 2차원 최대 증가 수열 C++ (0) | 2024.07.07 |
[코드트리] 최대 증가 부분 수열 C++ (0) | 2024.07.05 |