HDU - 6341 Let Sudoku Rotate (DFS+剪枝)

Let Sudoku Rotate

题目链接: Problem J. Let Sudoku Rotate

题意

给你一个16 * 16的矩阵,里面出现的数为十六进制的1到F,为数独分布,有人将其任意个4 * 4的单独小块逆旋转任意多次,现在,需要我们将其顺时针还原,问最少还原几次。


思路

直接dfs+可行性剪枝即可,因为在数独中,剪枝效率高。


代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 20;
int T, ans, tot;
char st[N][N], tmp[N][N];
int vis[N];

void rot(int x, int y) {
    for (int i = x; i < x + 4; ++i)
        for (int j = y; j < y + 4; ++j)
            tmp[x + j % 4][y + 3 - i % 4] = st[i][j];

    for (int i = x; i < x + 4; ++i)
        for (int j = y; j < y + 4; ++j)
            st[i][j] = tmp[i][j];
}

bool check(int a, int b) {
    for (int i = a; i < a + 4; ++i) {
        tot++;
        for (int j = 0; j < b+4; ++j) {
            if (vis[st[i][j]] == tot)
                return 0;
            vis[st[i][j]] = tot;
        }
    }
    for (int i = b; i < b + 4; ++i) {
        tot++;
        for (int j = 0; j < a+4; ++j) {
            if (vis[st[j][i]] == tot)
                return 0;
            vis[st[j][i]] = tot;
        }
    }
    return 1;
}

void dfs(int x, int y, int sum) {
    if (sum>=ans) return ;
    if (x == 4) {
        ans = min(ans, sum);
        return;
    }
    if (y == 4) {
        dfs(x+1,0,sum);
        return ;
    }
    for (int i = 0; i < 4; ++i) {
        if (check(x*4,y*4)) dfs(x,y+1,sum+i); //如果可以就继续
        rot(x*4,y*4);
    }
}

int main() {
    scanf("%d", &T);
    while (T--) {
        for (int i = 0; i < 16; ++i) scanf("%s", st[i]);
        for (int i = 0; i < 16; ++i)
            for (int j = 0; j < 16; ++j)
                if (isdigit(st[i][j])) st[i][j] -= 48;
                else                   st[i][j] -= 55;
        ans = 50;
        dfs(0, 0, 0);
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40513946/article/details/81367297