본문 바로가기

Coding/백준

4963번 섬의 개수

 BFS 기본 문제. 

 

 

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
#include <iostream>
#include <vector>
#include <queue>
#define visited true
#define Non_visited false
#define MAX 51
 
using namespace std;
 
typedef pair<int,int> pir;
int xx[4]={1,0,-1,0};
int yy[4]={0,1,0,-1};
int xx2[4]={1,-1,1,-1};
int yy2[4]={1,-1,-1,1};
int map[MAX][MAX];
bool flag;
int w,h;
vector<int> answer;
queue<pir> q;
bool check[MAX][MAX];
int cnt;
 
void bfs(){
    
    while(!q.empty()){
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        
        check[x][y]=true;
        
        for(int i=0;i<4;i++){
            int nx = x + xx[i];
            int ny = y + yy[i];
            
            int nx2 = x + xx2[i];
            int ny2 = y + yy2[i];
            
            if(0<=nx && nx<&& 0<=ny && ny<&& !check[nx][ny] && map[nx][ny]==1){
                check[nx][ny]=true;
                q.push(pir(nx,ny));
            }
            
            if(0<=nx2 && nx2<&& 0<=ny2 && ny2<&& !check[nx2][ny2] && map[nx2][ny2]==1){
                check[nx2][ny2]=true;
                q.push(pir(nx2,ny2));
            }
 
        }
    }
}
void reset(int a, int b){
    cnt=0;
    for(int i=0;i<a;i++){
        for(int j=0;j<b;j++){
            check[i][j]=false;
        }
    }
}
 
int main(){
    while(!flag){
        cin >> w >> h;
        
        if(w==0 && h==0){
            break;
        }
        else{
            for(int i=0;i<h;i++){
                for(int j=0;j<w;j++){
                    cin >> map[i][j];
                }
            }
        }
        for(int i=0;i<h;i++){
            for(int j=0;j<w;j++){
                if(!check[i][j] && map[i][j]==1){
                    q.push(pir(i,j));
                    bfs();
                    cnt++;
                }
            }
        }
        answer.push_back(cnt);
        reset(h,w);
    }
    
    for(int i=0;i<answer.size();i++){
        cout << answer[i] << endl;
    }
}
 
cs

'Coding > 백준' 카테고리의 다른 글

2798번 블랙잭  (0) 2021.01.20
6603번 로또  (0) 2021.01.20
2966번 찍기  (0) 2020.07.15
2858번 기숙사 바닥  (0) 2020.07.14
1748번 수 이어 쓰기 1  (0) 2020.07.12