题意:
给一个16*16的数独,每个4*4的子模块可能被逆时针转动过,问至少转动了多少次。
思路:
通过模拟顺时针还原子模块,看看需要多少步。
dfs枚举每一行的四个4*4的子模块的转动次数,然后检验当前转动是否使得这一行和之前的行、列满足数独要求。
加上最优性剪枝和数独判断剪枝之后,dfs复杂度不高。
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <map>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <sstream>
#define pb push_back
#define X first
#define Y second
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pii pair<int,int>
#define qclear(a) while(!a.empty())a.pop();
#define lowbit(x) (x&-x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define mst(a,b) memset(a,b,sizeof(a))
#define cout3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl
#define cout2(x,y) cout<<x<<" "<<y<<endl
#define cout1(x) cout<<x<<endl
#define IOS std::ios::sync_with_stdio(false)
#define SRAND srand((unsigned int)(time(0)))
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
using namespace std;
const double PI=acos(-1.0);
const int INF=0x3f3f3f3f;
const ll mod=1e9+7;
const double eps=1e-8;
const int maxn=55;
const int maxm=10005;
char maps[maxn][maxn];
char buf[maxn][maxn];
void rot(int x,int y) {
x=(x-1)*4+1;
y=(y-1)*4+1;
for(int i=x; i<x+4; i++) {
for(int j=y; j<y+4; j++) {
int nowx=i-x+1;
int nowy=j-y+1;
nowx=5-nowx;
buf[nowy][nowx]=maps[i][j];
}
}
for(int i=x; i<x+4; i++) {
for(int j=y; j<y+4; j++) {
maps[i][j]=buf[i-x+1][j-y+1];
}
}
}
int getid(char ch) {
if(ch>='0'&&ch<='9')
return ch-'0';
else
return ch-'A'+10;
}
bool vis[maxn];
bool check(int line) {
int x=(line-1)*4+1;
for(int i=x; i<x+4; i++) {
mst(vis,0);
for(int j=1; j<=16; j++) {
if(vis[getid(maps[i][j])]) {
return 0;
} else {
vis[getid(maps[i][j])]=1;
}
}
}
for(int j=1;j<=16;j++){
mst(vis,0);
for(int i=1;i<x+4;i++){
if(vis[getid(maps[i][j])]) {
return 0;
} else {
vis[getid(maps[i][j])]=1;
}
}
}
return 1;
}
int ans;
void dfs(int line,int cnt) {
if(cnt>ans)
return ;
if(line==5) {
ans=min(ans,cnt);
}
for(int i=0; i<4; i++,rot(line,1)) {
for(int j=0; j<4; j++,rot(line,2)) {
for(int k=0; k<4; k++,rot(line,3)) {
for(int l=0; l<4; l++,rot(line,4)) {
if(check(line)) {
dfs(line+1,cnt+i+j+k+l);
}
}
}
}
}
return ;
}
void solve() {
int t;
sd(t);
getchar();
while(t--) {
for(int i=1; i<=16; i++) {
for(int j=1; j<=16; j++) {
maps[i][j]=getchar();
}
getchar();
}
ans=INF;
dfs(1,0);
printf("%d\n",ans);
}
return ;
}
int main() {
#ifdef LOCAL
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#else
// freopen("","r",stdin);
// freopen("","w",stdout);
#endif
solve();
return 0;
}