알고리즘

[알고리즘] 백준 17406 - 배열 돌리기 4 (C++)

blueberrysoda 2025. 1. 27. 22:48

[문제 링크] : https://www.acmicpc.net/problem/17406

#include <iostream>
using namespace std;

int N, M, K;
int Ans = 1234567890;
int Arr[51][51];
int Tmp[51][51];
int Cal[6][3];
bool Check[6];
int Order[6];

int calc(){
    int res = 1234567890;
    for(int i=1; i<=N; i++){
        int sum = 0;
        for(int j=1; j<=M; j++){
            sum += Tmp[i][j];
        }
        res = min(res, sum);
    }

    return res;
}

void rotate(){
    for(int o=0; o<K; o++){
        int y = Cal[Order[o]][0];
        int x = Cal[Order[o]][1];
        int s = Cal[Order[o]][2];

        for(int i=1; i<=s; i++){
            int LT = Tmp[y - i + 1][x - i];
            int RT = Tmp[y - i][x + i - 1];
            int LB = Tmp[y + i][x - i + 1];
            int RB = Tmp[y + i - 1][x + i];

            for(int j=x+i-1; j>x-i; j--){
                Tmp[y - i][j] = Tmp[y - i][j - 1];
            }
            for(int j=x-i+1; j<x+i; j++){
                Tmp[y + i][j] = Tmp[y + i][j + 1];
            }
            for(int j=y-i+1; j<y+i; j++){
                Tmp[j][x - i] = Tmp[j + 1][x - i];
            }
            for(int j=y+i-1; j>y-i; j--){
                Tmp[j][x + i] = Tmp[j - 1][x + i];
            }

            Tmp[y - i][x - i] = LT;
            Tmp[y - i][x + i] = RT;
            Tmp[y + i][x - i] = LB;
            Tmp[y + i][x + i] = RB;
        }
    }
    return;
}

void solve(int n){
    if(n == K){
        for(int i=1; i<=N; i++){
            for(int j=1; j<=M; j++){
                Tmp[i][j] = Arr[i][j];
            }
        }

        rotate();

        int val = calc();
        Ans = min(Ans, val);
        return;
    }

    for(int i=0; i<K; i++){
        if(Check[i] == false){
            Check[i] = true;
            Order[n] = i;
            solve(n + 1);
            Check[i] = false;
        }
    }

    return;
}

int main(){
    cin >> N >> M >> K;
    for(int i=1; i<=N; i++){
        for(int j=1; j<=M; j++){
            cin >> Arr[i][j];
        }
    }

    for(int i=0; i<K; i++){
        cin >> Cal[i][0] >> Cal[i][1] >> Cal[i][2];
    }

    solve(0);

    cout << Ans << "\n";

    return 0;
}