-
[4963] 섬의 개수BOJ 2021. 10. 16. 09:55
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
<문제>
4방향과 8방향의 차이는 방향데이터뿐이다. 항상 시계방향이나 반시계방향을 지키도록 구현하는게 좋다.
테스트케이스가 여러개 존재하는 입력인 경우, queue나 visit의 초기화를 매번 진행해주어야 한다.
특히, 조기리턴이 존재하는 경우에는 더욱 유의해야 할것이, queue가 비어있지 않은채로 bfs가 종료되기도 한다.
<소스코드>
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#include <stdio.h>#include <string.h>#include <queue>using namespace std;int w, h;int a[53][53];bool visit[53][53];int dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1};int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1};queue<int> q;void f(int sy, int sx) {int i, ty, tx, y, x;q.push(sy);q.push(sx);visit[sy][sx] = true;while (!q.empty()) {ty = q.front();q.pop();tx = q.front();q.pop();for (i = 0; i < 8; i++) {y = ty + dy[i];x = tx + dx[i];if (y < 0 || x < 0 || y >= w || x >= h) continue;if (visit[y][x] == false && a[y][x] == 1) {q.push(y);q.push(x);visit[y][x] = true;}}}return;}int main(void) {int i, j, cnt;while (1) {scanf("%d %d", &h, &w);if (w == 0 && h == 0) break;memset(visit, false, sizeof(visit));while (!q.empty()) q.pop();cnt = 0;for (i = 0; i < w; i++)for (j = 0; j < h; j++) scanf("%d", &a[i][j]);for (i = 0; i < w; i++) {for (j = 0; j < h; j++) {if (visit[i][j] == false && a[i][j] == 1) {f(i, j);cnt++;}}}printf("%d\n", cnt);}return 0;}cs 'BOJ' 카테고리의 다른 글
[7562] 나이트의 이동 (0) 2021.10.16 [2178] 미로 탐색 (0) 2021.10.16 [7569] 토마토 (0) 2021.10.16 [2667] 단지번호붙이기 (0) 2021.10.16 [16946] 벽 부수고 이동하기 4 (0) 2021.10.16