728x90
반응형
문제 출처 : https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
풀이
dfs, bfs 모두 사용 가능하며 bfs로 해결하였다.
코드
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int w, h;
int arr[50 + 1][50 + 1];
bool check[50 + 1][50 + 1];
queue<pair<int, int>> q;
int dx[8] = {-1, 1, 0, 0, 1, 1, -1, -1};
int dy[8] = {0, 0, -1, 1, -1, 1, 1, -1};
void bfs(){
while(!q.empty()){
int y = q.front().first;
int x = q.front().second;
q.pop();
for(int i = 0; i < 8; i++){
int ny = y + dy[i];
int nx = x + dx[i];
if(nx <= 0 || ny <= 0 || nx > w || ny > h)
continue;
if(arr[ny][nx] && !check[ny][nx]){
q.push({ny, nx});
check[ny][nx] = true;
}
}
}
}
int main(){
ios::sync_with_stdio(false); cin.tie(NULL);
while (true){
cin >> w >> h;
int ans = 0;
if(!w && !h) break;
for(int i = 1; i <= h; i++){
for(int j = 1; j <= w; j++)
cin >> arr[i][j];
}
for(int i = 1; i <= h; i++){
for(int j = 1; j <= w; j++){
if(!check[i][j] && arr[i][j]){
q.push({i, j});
check[i][j] = true;
bfs();
ans++;
}
}
}
cout << ans << '\n';
memset(check, 0, sizeof(check));
}
return 0;
}
728x90
반응형
'Tech > Algorithm' 카테고리의 다른 글
[BOJ] 백준 2573 빙산 c++ (bfs, 구현) (0) | 2022.12.30 |
---|---|
[BOJ] 백준 14500 테트로미노 c++ (구현, 백트래킹) (0) | 2022.07.21 |
[BOJ] 백준 1987 알파벳 c++ (dfs, 백트래킹, 그래프) (0) | 2022.01.17 |
[BOJ] 백준 1182 부분수열의 합 c++ (dfs, 백트래킹, 브루트포스) (0) | 2022.01.17 |
[BOJ] 백준 1759 암호 만들기 c++ (dfs, 백트래킹, 브루스포스) (0) | 2022.01.16 |