https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수
www.acmicpc.net
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int N;
int map[30][30];
bool chk[30][30];
int cnt=0;
vector <int> solution;
vector <int> dy={-1,0,1,0};
vector <int> dx={0,1,0,-1};
void bfs(int y, int x){
queue <pair<int, int>> q;
q.push(make_pair(y,x));
chk[y][x]=true;
while(!q.empty()){
pair<int, int> p;
p = q.front();
q.pop();
cnt++;
for(int i=0;i<4;i++){
int ny = p.first+dy[i];
int nx = p.second+dx[i];
if(map[ny][nx]==1&&chk[ny][nx]==false){
q.push(make_pair(ny,nx));
chk[ny][nx]=true;
}
}
}
}
int main(){
freopen("input.txt","r",stdin);
cin>>N;
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
scanf("%1d", &map[i][j]);
}
}
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
cnt=0;
if(map[i][j]==1 && chk[i][j]==false){
bfs(i, j);
solution.push_back(cnt);
}
}
}
sort(solution.begin(),solution.end());
cout<<solution.size()<<"\n";
for(int i=0;i<solution.size();i++){
cout << solution[i] <<"\n";
}
return 0;
}
'개발자 > algorithm' 카테고리의 다른 글
이진 탐색 알고리즘 - binarySearch (c++) (0) | 2020.04.04 |
---|---|
백준 2667번 : 단지번호붙이기 - dfs 기본문제 (c++) (0) | 2020.04.01 |
2019 카카오 코딩테스트 1번 : 오픈채팅방 (c++) (0) | 2020.03.20 |
백준 1010번 : 다리 놓기 (c++) (0) | 2020.03.20 |
2018 카카오 코딩테스트 1번 : 비밀지도 (c++) (0) | 2020.03.18 |