最少多少次小区域逆时针旋转操作能使给出的16*16方格经旋转后满足数独条件。
思路:
每一个4*4小格子都可以判断一下是否还需旋转九十度:若是此小格子与它前面的每行都不冲突,与它前面的每一列都不冲突,则这个小格子不需要旋转九十度。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
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;
}