Little Jay

[C++] 백준 4963번 - 섬의 개수 본문

카테고리 없음

[C++] 백준 4963번 - 섬의 개수

Jay, Lee 2022. 3. 18. 15:37

BFS로 구현했다. (DFS 싫어)

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

bool arr[51][51];
bool visited[51][51];
const int dx[] = { -1, -1, -1, 0, 1, 1, 1, 0 };
const int dy[] = { -1, 0, 1, 1, 1, 0, -1, -1  };

int w, h;

int bfs(int x, int y) {
	if (arr[x][y] == 0) return 0;
	if (visited[x][y]) return 0;
	queue<pair<int, int>> q;
	q.push({ x, y });
	visited[x][y] = 1;
	while (!q.empty()) {
		auto current = q.front();
		q.pop();
		for (int dir = 0; dir < 8; dir++) {
			int nx = current.first + dx[dir];
			int ny = current.second + dy[dir];

			if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
			if (visited[nx][ny] || arr[nx][ny] == 0) continue;
			visited[nx][ny] = 1;
			q.push({ nx, ny });
		}
	}

	return 1;
}


int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	while (true) {
		cin >> w >> h;
		if (w == 0 && h == 0) break;
		int land = 0;

		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				cin >> arr[i][j];
			}
		}
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				land += bfs(i, j);
			}
		}

		cout << land << endl;
		memset(arr, 0, sizeof(arr));
		memset(visited, false, sizeof(visited));
	}

	return 0;
}
Comments