4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
int a[100][100];
int d[100][100];
int dx[] = {0,0,1,-1,1,1,-1,-1};
int dy[] = {1,-1,0,0,1,-1,1,-1};
int n,m;
void bfs(int x, int y, int cnt) {
queue<pair<int,int>> q;
q.push(make_pair(x,y));
d[x][y] = cnt;
while (!q.empty()) {
x = q.front().first;
y = q.front().second;
q.pop();
for (int k=0; k<8; k++) {
int nx = x+dx[k];
int ny = y+dy[k];
if (0 <= nx && nx < n && 0 <= ny && ny < m) {
if (a[nx][ny] == 1 && d[nx][ny] == 0) {
q.push(make_pair(nx,ny));
d[nx][ny] = cnt;
}
}
}
}
}
int main() {
while (true) {
scanf("%d %d",&m,&n);
if (n == 0 && m == 0) break;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
scanf("%1d",&a[i][j]);
d[i][j] = 0;
}
}
int cnt = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (a[i][j] == 1 && d[i][j] == 0) {
bfs(i, j, ++cnt);
}
}
}
printf("%d\n",cnt);
}
return 0;
}
'Problem set' 카테고리의 다른 글
[백준] 7576 토마토 (0) | 2021.02.20 |
---|---|
[백준] 2178 미로 탐색 (0) | 2021.02.20 |
[백준] 2667 단지번호붙이기 (0) | 2021.02.20 |
[백준] 1707 이분 그래프 (0) | 2021.02.20 |
[백준] 11724 연결 요소의 개수 (0) | 2021.02.20 |