알고리즘 공부

백준 1012번 유기농 배추

빵어 2023. 3. 10. 22:11
#include <iostream>
#include <vector>

using namespace std;

vector<int> m, n, k;
bool graph[51][51];

bool dfs(int x, int y, int num) {
	if (x <= -1 || x >= m[num] || y <= -1 || y >= n[num])
		return false;

	if (graph[x][y] == true) {
		graph[x][y] = false;

		dfs(x - 1, y, num);
		dfs(x + 1, y, num);
		dfs(x, y - 1, num);
		dfs(x, y + 1, num);

		return true;
	}
	return false;
}

int main() {
	int t;
	cin >> t;

	m.resize(t);
	n.resize(t);
	k.resize(t);
	vector<int> result(t);
	
	for (int i = 0; i < t; ++i) {
		cin >> m[i] >> n[i] >> k[i];

		int x, y;
		for (int j = 0; j < k[i]; ++j) {
			cin >> x >> y;
			graph[x][y] = true;
		}
		
		for (int x = 0; x < m[i]; ++x)
			for (int y = 0; y < n[i]; ++y)
				if (dfs(x, y, i))
					++result[i];
	}

	for (int a : result)
		cout << a << endl;

	return 0;
}

범위를 잘 설정하자

 

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

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 

www.acmicpc.net