본문 바로가기
[C++] 알고리즘 교육/19. BFS(기본)

[알고리즘 19.1.6] BFS - 단지번호 붙이기

by 안산학생 2019. 8. 12.

문제


<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

 

입력


첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

 

출력


첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

 

예제 입력

7
0110100
0110101
1110101
0000111
0100000
0111110
0111000

예제 출력

3 7 8 9

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
 
//배열, 확인배열, 입력값
const int MAX = 30;
int arr[MAX][MAX];
int check[MAX][MAX];
int n;
 
//좌표를 구현한 구조체
typedef struct coor{
  int n;
  int m;
  coor(){};
  coor(int _n, int _m) : n(_n), m(_m){};
}coor;
 
//구조체 Queue 선언
queue <coor> q;
 
//4부분을 방문할 배열
int dx[4= {-1,1,0,0};
int dy[4= {0,0,1,-1};
 
//단지 번호 붙일 변수
int count1 = 0;
int sum[676]={0,};
int sumCount = 0;
 
bool inside(int a, int b){
  return (a>=0 && a<n) && (b>=0 && b<n);
}
 
void BFS(){
  if(q.empty()) return;
  count1++;
  int a, b;
  coor now = q.front();
  q.pop();
  a = now.n;
  b = now.m;
  
  int nx, ny;
  coor nowPush;
  for(int i=0; i<4; i++){
    nx = a + dx[i];
    ny = b + dy[i];
    if(inside(nx,ny) && arr[nx][ny]==1 && check[nx][ny]==0){
      nowPush.n = nx;
      nowPush.m = ny;
      q.push(nowPush);
      check[nx][ny] = 1;
    }
    BFS();
  }
  if(!q.empty()) BFS();
}
 
void functionA(int a){
  for(int i=0; i<a; i++){
    for(int j=0; j<a; j++){
      if(check[i][j]==0 && arr[i][j]==1){
        count1 = 0;
        q.push(coor(i,j));
        check[i][j]=1;
        BFS();
        //단지에 값 넣어주기
        sum[sumCount] = count1;
        sumCount++;
      }
      
    }
  }
}
 
int main(){
  
  cin>>n;
  for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
      scanf("%1d",&arr[i][j]);
    }
  }
  
  functionA(n);
  
  sort(sum, sum+sumCount);
  cout<<sumCount<<endl;
  for(int i=0; i<sumCount; i++){
    cout<<sum[i]<<endl;
  }
  
  return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

댓글