알고리즘/완전 탐색

백준 1012번 : 유기농 배추

Jason95 2021. 1. 2. 19:03

문제 링크 : acmicpc.net/problem/1012

내 풀이(2021. 1. 2.) :

#include <iostream>

using namespace std;

bool exist[50][50];
bool visit[50][50];
int counts = 0;

int X, Y, K;

void search(int y, int x, bool first) {
	if (y == -1 || x == -1 || y == Y || x == X) return;
	if (exist[y][x] == false) return;
	if (visit[y][x] == true) {
		return;
	}
	else {
		if (first == true) {
			counts++;
			first = false;
		}
	}

	visit[y][x] = true;

	search(y - 1, x, false);
	search(y + 1, x, false);
	search(y, x - 1, false);
	search(y, x + 1, false);
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	
	int T; cin >> T;
	for (int i = 0; i < T; i++) {
		cin >> X >> Y >> K;
		for (int j = 0; j < K; j++) {
			int x, y; cin >> x >> y;
			exist[y][x] = true;
		}

		for (int i = 0; i < Y; i++) {
			for (int j = 0; j < X; j++) {
				search(i, j, true);
			}
		}

		/*
		// 확인용
		for (int i = 0; i < Y; i++) {
			for (int j = 0; j < X; j++) {
				cout << (int)visit[i][j];
			}
			cout << endl;
		}
		*/

		// 초기화
		for (int i = 0; i < Y; i++) {
			for (int j = 0; j < X; j++) {
				exist[i][j] = false;
				visit[i][j] = false;
			}
		}

		cout << counts << endl;
		counts = 0;
	}
	return 0;
}

재귀 함수가 첫번째로 호출될 때만 count 하도록 search의 3번째 인자를 first로 만들었다.