백준 문제풀이

백준 1012번 - C++

diligent_gideok 2022. 4. 30. 06:28
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int board[51][51];
int vis[51][51];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };


int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0);
	queue<pair<int, int> > Q;
	int test;
	cin >> test;
	for (int i = 0; i < test; i++) {
		int n, m, k;
		int val=0;
		int board[51][51] = {};
		int vis[51][51] = {};
		cin >> n >> m >> k;
		while (k--) {
			int a, b;
			cin >> a >> b;
			board[b][a] = 1;
		}
		
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {// for 문으로 다 돌면서 배추가 심어진(board 값이 1인) 곳 찾고 찾으면 while문 돌리기
				if (board[i][j] == 1 && !vis[i][j]) {
					val++;
					//cout << val << ' ';
					vis[i][j] = 1;
					Q.push({ i,j });
				}
				while (!Q.empty()) {
					pair<int, int> cur = Q.front(); Q.pop();
					//cout << '(' << cur.X << ", " << cur.Y << ") -> ";
					for (int dir = 0; dir < 4; dir++) {
						int nx = cur.X + dx[dir];
						int ny = cur.Y + dy[dir];
						if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
						if (board[nx][ny] != 1||vis[nx][ny]) continue;
						vis[nx][ny] = 1;
						Q.push({ nx,ny });
					}
				}
			}
		}
		cout << val << "\n";
	}
}

'백준 문제풀이' 카테고리의 다른 글

백준 2468번 - C++  (0) 2022.04.30
백준 1697번 - C++  (0) 2022.04.30
백준 10799번 - C++  (0) 2022.04.30
백준 4949번 - C++  (0) 2022.04.30
백준 11003번 - C++  (0) 2022.04.30