Overfitting

Algorithm2025-03-08

BOJ 18809 Gaaaaaaaaaarden (C++)

배양액을 뿌릴 땅을 고른 뒤 두 색이 동시에 퍼지는 순간을 세는 백트래킹과 BFS 풀이예요.

체감 난이도는 정말 골드가 아니라 플래티넘이었어요.
푸는 데 시간이 꽤 오래 걸렸고, 특히 BFS가 까다로웠던 문제예요.

문제

18809번: Gaaaaaaaaaardenboj.ma

요약하면 다음과 같아요.

  1. 호수와 땅이 있고, 땅 중에서도 배양액을 뿌릴 수 있는 땅이 따로 있어요.

  2. 배양액은 초록, 빨강 두 종류이고 둘 다 사방으로 퍼져 나가요.

  3. 먼저 지나간 배양액이 있으면 못 지나가요.

  4. 초록, 빨강 배양액이 동시에 만나면 꽃이 펴요.

→ 꽃의 최대 개수를 출력하는 문제예요.

풀이

  1. 배양액을 뿌릴 땅을 고르는 백트래킹이에요.

  2. 초록, 빨강 배양액을 배치하는 백트래킹이에요.

  3. 배양액을 퍼뜨리는 BFS예요.

코드

#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
#define MAX 50
#define GREEN 0
#define RED 1
#define STOP -999
using namespace std;

void selectLand(int, int);      // 배양액을 뿌릴 수 있는 땅의 조합을 구하는 함수
void selectLocation(int, int);  // 고른 땅 중 배양액을 뿌릴 조합을 구하는 함수
int BFS();                     // G, R의 배양액을 뿌리고 꽃의 개수를 전달하는 함수

struct Location {
    int X, Y;
};

struct Fluid {
    int X, Y;
    int color;  // 초록(G) -> 0, 빨강(R) -> 1
    int time;
};

int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

vector<Location> fluids;
vector<Location> selected;
vector<Location> green;
vector<Location> red;
int N, M, G, R;
int graph[MAX][MAX];
int visited[MAX][MAX][2];
int maxFlower;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> N >> M >> G >> R;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cin >> graph[i][j];
            if (graph[i][j] == 2) fluids.push_back({i, j});
        }
    }

    selectLand(0, 0);
    cout << maxFlower;
    return 0;
}

void selectLand(int start, int depth) {
    if (depth == G + R) {
        selectLocation(0, 0);  // 배양액을 뿌릴 위치 선택
        return;
    }

    for (int i = start; i < fluids.size(); i++) {
        selected.push_back({fluids[i].X, fluids[i].Y});
        selectLand(i + 1, depth + 1);
        selected.pop_back();  // 백트래킹
    }
}

void selectLocation(int index, int count) {
    if (count == G) {
        red.clear();  // 새로운 초록색 조합마다 빨간색을 초기화

        // 초록색 배양액(G) 이 아닌 땅을 빨간 땅(R) 으로 배정
        for (int i = 0; i < selected.size(); i++) {
            bool isGreen = false;
            for (int j = 0; j < green.size(); j++) {
                if (selected[i].X == green[j].X &&
                    selected[i].Y == green[j].Y) {
                    isGreen = true;
                    break;
                }
            }
            if (!isGreen) {
                red.push_back(selected[i]);
            }
        }

        int flower = BFS();
        maxFlower = max(maxFlower, flower);
        return;
    }

    for (int i = index; i < selected.size(); i++) {
        green.push_back(selected[i]);
        selectLocation(i + 1, count + 1);
        green.pop_back();  // 백트래킹
    }
}

int BFS() {
    queue<Fluid> que;
    memset(visited, -1, sizeof(visited));
    int flower = 0;

    for (Location g : green) {
        que.push({g.X, g.Y, GREEN, 0});
        visited[g.X][g.Y][GREEN] = 0;
    }
    for (Location r : red) {
        que.push({r.X, r.Y, RED, 0});
        visited[r.X][r.Y][RED] = 0;
    }

    while (!que.empty()) {
        Fluid fluid = que.front();
        que.pop();

        int fx = fluid.X;
        int fy = fluid.Y;
        int fcolor = fluid.color;
        int ftime = fluid.time;

        // 이미 꽃이 핀 곳은 카운트 및 확산 중지
        if (visited[fx][fy][GREEN] == visited[fx][fy][RED] &&
            visited[fx][fy][GREEN] != -1) {
            // 중복 방지를 위하여 초록색으로 고정
            if (fcolor == GREEN) flower++;
            continue;
        }

        for (int i = 0; i < 4; i++) {
            int newX = fx + dx[i];
            int newY = fy + dy[i];

            if (newX < 0 || newY < 0 || newX >= N || newY >= M) continue;
            if (graph[newX][newY] == 0 || visited[newX][newY][fcolor] != -1) continue;

	    // 새로운 배양액이 만났을 때 카운트 및 확산 중지
            if (visited[newX][newY][GREEN] != -1 && visited[newX][newY][RED] != -1) {
                if (visited[newX][newY][GREEN] == visited[newX][newY][RED] &&
                    visited[newX][newY][GREEN] == ftime + 1) {
                    visited[newX][newY][GREEN] = visited[newX][newY][RED] = STOP;
                    flower++;
                }
                continue;
            }

            if (visited[newX][newY][fcolor] == -1) {
                visited[newX][newY][fcolor] = ftime + 1;
                que.push({newX, newY, fcolor, ftime + 1});
            }
        }
    }

    return flower;
}