题意:0可以跟左上,上,下,右下,换然后要求是否可以在20步之内换成原始的样子
题解:如果单向搜索的话最恶劣的情况时间复杂度0(4^20)这样搜索肯定会超时,那么我们可以预处理重原始的搜索10步内的各种情况用6进制的hash值存取即可因为最大值为5,然后正向搜索用hash值标记这个状态是否到达过,如果这个状态在预处理里面那么ans = min(ans,map[ret]+ft.step);如果ft.step超过10步就可以不用再搜索了,因为如果有早就在预处理的hash表里面可以找到.
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef unsigned long long ul;
const int inf = 0x3f3f3f3f;
struct node{
int v[6][6];
int step;
int x,y;
ul hash(){
ul ans = 0;
for(int i = 0; i < 6; i++)
for(int j = 0; j <= i; j++)
ans = ans*6+v[i][j];
return ans;
}
}a;
map<ul,int>mp;
set<ul>st;
int x_move[4] = {1,-1,1,-1};
int y_move[4] = {0,0,1,-1};
void init(){
node ft;
queue<node>q;
ft.step = 0;
ft.x = 0;
ft.y = 0;
for(int i = 0; i < 6; i++)
for(int j = 0; j <= i; j++)
ft.v[i][j] = i;
mp[ft.hash()] = 0;
q.push(ft);
while(!q.empty()){
ft = q.front();
q.pop();
if(ft.step>=10)
continue;
ft.step++;
int x = ft.x,y = ft.y;
for(int i = 0; i < 4; i++){
int ex = x+x_move[i];
int ey = y+y_move[i];
if(ex>=0&&ey>=0&&ex<=5&&ey<=5&&ey<=ex){
swap(ft.v[x][y],ft.v[ex][ey]);
ul ret = ft.hash();
ft.x = ex;
ft.y = ey;
if(!mp.count(ret)){
mp[ret] = ft.step;
q.push(ft);
}
swap(ft.v[x][y],ft.v[ex][ey]);
}
}
}
}
void bfs(){
node ft = a;
queue<node>q;
st.insert(ft.hash());
q.push(ft);
int ans = inf;
while(!q.empty()){
ft = q.front();
ul ret = ft.hash();
q.pop();
if(mp.count(ret))
ans = min(ans,mp[ret]+ft.step);
if(ft.step>=10)
continue;
ft.step++;
int x = ft.x,y = ft.y;
for(int i = 0; i < 4; i++){
int ex = x+x_move[i];
int ey = y+y_move[i];
if(ex>=0&&ey>=0&&ex<=5&&ey<=5&&ey<=ex){
swap(ft.v[x][y],ft.v[ex][ey]);
ul ret = ft.hash();
ft.x = ex;
ft.y = ey;
if(st.find(ret)==st.end()){
st.insert(ret);
q.push(ft);
}
swap(ft.v[x][y],ft.v[ex][ey]);
}
}
}
ans == inf?puts("too difficult"):printf("%d\n",ans);
}
int main(){
int t;
mp.clear();
init();
a.step = 0;
scanf("%d",&t);
while(t--){
for(int i = 0; i < 6; i++)
for(int j = 0; j <= i; j++){
scanf("%d",&a.v[i][j]);
if(a.v[i][j]==0)
a.x = i,a.y = j;
}
st.clear();
bfs();
}
return 0;
}