알고리즘

C++ 알고리즘 - 백준 1012 유기농 배추

마루설아 2025. 1. 7. 21:14

https://www.acmicpc.net/problem/1012

 

#include <bits/stdc++.h>
#define endl "\n"

using namespace std;

int farm[52][52];
int cnt;

void find(int x, int y) {
	if (farm[x + 1][y] == 1) {
		farm[x + 1][y] = -1;
		find(x + 1, y);
	}

	if (farm[x][y + 1] == 1) {
		farm[x][y+1] = -1;
		find(x, y + 1);
	}

	if (x > 0) {
		if (farm[x - 1][y] == 1) {
			farm[x - 1][y] = -1;
			find(x - 1, y);
		}
	}

	if (y > 0) {
		if (farm[x][y - 1] == 1){
			farm[x][y - 1] = -1;
			find(x, y - 1);
		}
	}

	else {
		return;
	}
}

int main(void) {
	/************** C++ Init **************/
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	/************** C++ Init **************/


	int input1, input2, input3, input4;
	int x, y;	

	cin >> input1;

	for (int i = 0; i < input1; i++) {
		cin >> input2 >> input3 >> input4;
		cnt = 0;
		
		for (int j = 0; j < input4; j++) {
			cin >> x >> y;
			farm[x][y] = 1;
		}

		for (int j = 0; j < input2; j++) {
			for (int k = 0; k < input3; k++) {
				if (farm[j][k] == 1) {
					farm[j][k] = -1;
					cnt++;
					find(j, k);
				}
			}
		}
		cout << cnt << endl;
	}
}

 

반례을 찾을 수 없다..