문제 링크 : 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로 만들었다.
'알고리즘 > 완전 탐색' 카테고리의 다른 글
백트래킹 개념 (0) | 2021.01.05 |
---|---|
백준 11724번 : 연결 요소의 개수 (0) | 2021.01.03 |
BFS 개념 (0) | 2020.12.21 |
백준 1074번 : Z (0) | 2020.12.17 |
백준 6603번 : 로또 (0) | 2020.12.16 |