<유기농 배추>
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <stack> #include <algorithm> int arr[50][50]; int gg, ss, kk; int check(int g, int s) { // 탐색 범위를 정해주어야 함. if (g >= 0 && gg > g && s >= 0 && ss > s) { return 1; } else { return 0; } } void remove(int g, int s) { // 재귀로 모든 이어져 있는 1 삭제 arr[s][g] = 0; int g1, s1, g2, s2, g3, s3, g4, s4; g1 = g + 1; s1 = s; //오 g2 = g - 1; s2 = s; //왼 g3 = g; s3 = s - 1;//아래 g4 = g; s4 = s + 1;//위 if (arr[s1][g1] == 1 && check(g1,s1)==1) { remove(g1, s1); } if (arr[s2][g2] == 1 && check(g2, s2) == 1) { remove(g2, s2); } if (arr[s3][g3] == 1 && check(g3, s3) == 1) { remove(g3, s3); } if (arr[s4][g4] == 1 && check(g4, s4) == 1) { remove(g4, s4); } //return; } int main() { int test; scanf("%d", &test); for (int t = 0; t < test; t++) { scanf("%d %d %d", &gg, &ss, &kk); for (int i = 0; i < 50; i++) { memset(arr[i], 0, sizeof(int) * 50); } for (int i = 0; i < kk; i++) { int x, y; scanf("%d %d", &x, &y); arr[y][x] = 1; } int point = 0; for (int i = 0; i < ss; i++) { // 모든 자리 순환 for (int j = 0; j < gg; j++) { if (arr[i][j] == 1) { point++; remove(j, i); } } } printf("%d\n", point); } return 0; }
방법 : 재귀를 통해 이어져 있는 모든 1을 삭제하여 0으로 만든다.
main의 for문에서는 2차원 배열을 돌며 1이 나올 때 마다 remove함수 실행, point++