알고리즘/DFS & BFS
백준[2667] 단지번호붙이기
HJ39
2023. 1. 11. 12:35
dfs를 이용하면 쉽게 풀지만 저장하는 배열을 동적할당하면 메모리오류가 발생한다..;
□ 소스 코드
#include <bits/stdc++.h>
int inputList[25][25]{0};
int aptCntList[25]{0};//단지 별 아파트 개수
int aptCnt; // 단지 개수
int apN;
bool dfs2667(int x,int y){
if(x<0 || y<0 || x>=apN|| y>=apN)
return false;
if(inputList[x][y] == 1){
inputList[x][y] = 0;
aptCntList[aptCnt]++;
dfs2667(x+1, y);
dfs2667(x-1, y);
dfs2667(x, y+1);
dfs2667(x, y-1);
return true;
}
return false;
}
void countNumApartment(){
cin>>apN;
for(int i=0;i<apN;i++){
for(int j=0;j<apN;j++){
scanf("%1d",&inputList[i][j]);
}
}
for(int i=0;i<apN;i++)
for(int j=0;j<apN;j++)
if(dfs2667(i,j)== true)
aptCnt++;
printf("%d\n",aptCnt);
sort(aptCntList, aptCntList+aptCnt);
for(int i=0;i<aptCnt;i++)
printf("%1d\n",aptCntList[i]);
}