[백준] 1012 유기농 배추

0

백준

목록 보기
223/271
post-thumbnail

[백준] 1012 유기농 배추

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

int N, M;
int board[55][55];
int visited[55][55];

bool inRange(int r, int c) {
	if (r < 0 || r >= N) return false;
	if (c < 0 || c >= M) return false;
	return true;
}

int dirR[4] = { 0, 0, 1, -1 };
int dirC[4] = { 1, -1, 0, 0 };

void bfs(int startR, int startC) {
	queue<pair<int, int>> q;
	q.push({ startR, startC });

	while (!q.empty()) {
		int curR = q.front().first; 
		int curC = q.front().second;
		q.pop();

		if (visited[curR][curC]) continue;
		visited[curR][curC] = 1;

		//상하좌우 인접한 칸 bfs
		for (int d = 0; d < 4; ++d) {
			int nextR = curR + dirR[d];
			int nextC = curC + dirC[d];

			if (!inRange(nextR, nextC)) continue;
			if (visited[nextR][nextC]) continue;
			if (board[nextR][nextC] == 0) continue;

			q.push({ nextR, nextC });
		}
	}
}


int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	int T;
	cin >> T;
	while (T--) {
		//board 초기화
		for (int i = 0; i <= 50; ++i) {
			for (int j = 0; j <= 50; ++j) {
				board[i][j] = 0;
				visited[i][j] = 0;
			}
		}

		//가로 M, 세로 N
		cin >> M >> N;

		int K;
		cin >> K;
		for(int i = 0; i<K; ++i){
			int x, y;
			cin >> x >> y;
			board[y][x] = 1;
		}

		//서로 인접한 배추들이 몇 군데 퍼져있는지 조사
		//방문되지 않은 배추의 좌표를 시작으로 bfs 반복
		int cnt = 0;
		for (int i = 0; i < N; ++i) {
			for (int j = 0; j < M; ++j) {
				if ((board[i][j] == 1) && (!visited[i][j])) {
					bfs(i, j);
					cnt++;
				}
			}
		}
		cout << cnt << "\n";
	}

	return 0;
}

profile
Be able to be vulnerable, in search of truth

0개의 댓글