Overfitting

Algorithm2026-02-09

BOJ 1207 종이 자르기 (C++)

다섯 조각의 종이로 정사각형 판을 빈틈없이 채우는 백트래킹 풀이예요.

오랜만에 올리는 글이에요.
그동안 졸업도 하고 취업도 하느라 오랜만에 글을 쓰게 되었어요.

💪 앞으로 자주 올려 볼게요.

문제

1207번: 종이 자르기boj.ma

L×L 격자판에 N×M 조각 5개를 배치해서 꽉 채우는 문제예요.

처음에는 그리디하게 큰 조각부터 배치해 보려고 했어요.
그런데 출력 조건에 사전 순으로 앞서는 것을 출력하라고 되어 있어서 백트래킹으로 탐색하게 되었어요.

풀이

  1. board를 순회하며 가장 먼저 만나는 빈 좌표 탐색

  2. 조각 평행 이동

  3. 1~5번 조각 백트래킹

  4. 유효성 검사 후 조각 배치

코드

#include <iostream>
#include <vector>
#define MAX 10
#define CUT 5
#define endl "\n"
using namespace std;

struct Piece {
    int R, C;
    vector<string> shape;
    int startR, startC;
};

struct Point {
    int R, C;
};

void arrange(int);             // 5조각을 맞추는 백트래킹 함수
Point findEmptyPlace();        // 조각을 배치할 비어있는 곳 찾기
bool check(int, int, int);     // 범위 + 겹치는지 확인
void put(int, int, int, int);  // 조각 채우기 (조각번호 or 0)

Piece pieces[CUT + 1];
bool used[CUT + 1];
int board[MAX][MAX];
int L, sharpCount;
bool isArranged;

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

    cin >> L;
    for (int i = 1; i <= CUT; i++) {
        cin >> pieces[i].R >> pieces[i].C;

        string str;
        bool isFirst = true;

        for (int r = 0; r < pieces[i].R; r++) {
            cin >> str;
            pieces[i].shape.push_back(str);

            for (int c = 0; c < pieces[i].C; c++) {
                if (str[c] == '#') {
                    sharpCount++;
                    if (isFirst) {
                        pieces[i].startR = r;
                        pieces[i].startC = c;
                        isFirst = false;
                    }
                }
            }
        }
    }

    if (sharpCount != L * L) {
        cout << "gg";
        return 0;
    }

    arrange(0);

    if (!isArranged) {
        cout << "gg";
    }

    return 0;
}

void arrange(int count) {
    // 모든 조각 (5개)를 모두 배치했을 때 -> 정답 출력
    if (count == CUT) {
        for (int i = 0; i < L; i++) {
            for (int j = 0; j < L; j++) {
                cout << board[i][j];
            }
            cout << endl;
        }
        isArranged = true;
        return;
    }

    Point empty = findEmptyPlace();
    if (empty.R == -1 && empty.C == -1) return;

    for (int p = 1; p <= CUT; p++) {
        if (used[p]) continue;

        int distR = empty.R - pieces[p].startR;
        int distC = empty.C - pieces[p].startC;

        if (check(p, distR, distC)) {
            // 모눈종이 배치하기 (p로 채우기)
            put(p, distR, distC, p);
            used[p] = true;

            // 다음 모눈종이
            arrange(count + 1);

            // 원상복구 (0으로 채우기, 이미 맞춰졌다면 복구 무시)
            if (isArranged) return;
            put(p, distR, distC, 0);
            used[p] = false;
        }
    }
}

Point findEmptyPlace() {
    for (int i = 0; i < L; i++) {
        for (int j = 0; j < L; j++) {
            if (board[i][j] == 0) return {i, j};
        }
    }
    return {-1, -1};
}

bool check(int idx, int distR, int distC) {
    for (int i = 0; i < pieces[idx].R; i++) {
        for (int j = 0; j < pieces[idx].C; j++) {
            if (pieces[idx].shape[i][j] == '#') {
                int newR = i + distR;
                int newC = j + distC;

                if (newR < 0 || newR >= L || newC < 0 || newC >= L || board[newR][newC] != 0)
                    return false;
            }
        }
    }
    return true;
}

void put(int idx, int distR, int distC, int value) {
    for (int i = 0; i < pieces[idx].R; i++) {
        for (int j = 0; j < pieces[idx].C; j++) {
            if (pieces[idx].shape[i][j] == '#') {
                board[i + distR][j + distC] = value;
            }
        }
    }
}