반응형
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
[ 문제풀이 ]
1. 섬을 입력받습니다.
2. 2중 for문을 통해 그림을 탐색하면서 1이면 bfs를 통해 이어진 섬을 모두 0으로 바꿔주고, cnt에 1을 더해줍니다.
3. cnt를 출력합니다.
[ 소스코드 ]
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 | #include<iostream> #include<queue> using namespace std; int arr[50][50]; int dy[8] = { 0,0,-1,1,-1,-1,1,1 }; int dx[8] = { -1,1,0,0,-1,1,1,-1 }; int w, h; void bfs(int y, int x) { queue<pair<int, int>> q; q.push({ y,x }); arr[y][x] = 0; while (!q.empty()) { const int y = q.front().first; const int x = q.front().second; q.pop(); for (int i = 0; i < 8; i++) { int yy = y + dy[i]; int xx = x + dx[i]; if (yy >= 0 && yy < h && xx >= 0 && xx < w) { if (arr[yy][xx] == 1) { arr[yy][xx] = 0; q.push({ yy,xx }); } } } } } int main() { while (1) { scanf("%d %d", &w, &h); if (w == 0 && h == 0) return 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { scanf("%d", &arr[i][j]); } } int cnt = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (arr[i][j] == 1) { bfs(i, j); cnt++; } } } printf("%d\n", cnt); } } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 21940번 - 가운데에서 만나기 (C++) (0) | 2023.03.23 |
---|---|
[ 백준 ] 14567번 - 선수과목 (Prerequisite) (C++) (0) | 2023.03.22 |
[ 백준 ] 10723번 - 판게아 1 (C++) (0) | 2023.03.20 |
[ 백준 ] 7044번 - Bad Cowtractors (C++) (0) | 2023.03.19 |
[ 백준 ] 9372번 - 상근이의 여행 (C++) (0) | 2023.03.18 |