-
Notifications
You must be signed in to change notification settings - Fork 0
/
4963.cpp
64 lines (57 loc) · 1.29 KB
/
4963.cpp
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
#include <iostream>
#include <queue>
#define PAIR pair<int,int>
using namespace std;
int dx[8]={-1,0,1,1,1,0,-1,-1};
int dy[8]={1,1,1,0,-1,-1,-1,0};
int w,h;
int graph[50][50];
int visited[50][50];
queue<PAIR> q;
void INIT(){
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
visited[i][j]=0;
}
}
}
void BFS(int x, int y){
q.push(PAIR(x,y));
visited[y][x]=1;
while(!q.empty()){
int vx = q.front().first;
int vy = q.front().second;
q.pop();
for(int i=0; i<8; i++){
int xx = vx+dx[i];
int yy = vy+dy[i];
if(xx>=0&&xx<w&&yy>=0&&yy<h&&graph[yy][xx]==1&&visited[yy][xx]==0){
q.push(PAIR(xx,yy));
visited[yy][xx]=1;
}
}
}
}
int main(){
while(1){
cin >> w>>h;
int cnt=0;
INIT();
if(w==0 && h==0) break;
for(int i=0; i<h;i++){
for(int j=0; j<w; j++){
int a; cin >> a;
graph[i][j]=a;
}
}
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
if(graph[i][j]==1&&visited[i][j]==0){
BFS(j,i);
cnt++;
}
}
}
cout << cnt << "\n";
}
}