1 题意
给定一个
4
×
8
4 \times 8
4×8的矩阵,其中第
1
1
1列为空,如下图所示:
先要求通过移动,使得所有数字有序,如下图所示:
现要求至少要移动多少步使得所有的数组有序。
2 思路
2.1 BFS
2.1.1 时间复杂度分析
最坏情况是所有状态都遍历到了,时间复杂度是 O ( 32 ! ) \mathcal{O}(32!) O(32!),并且 m a p map map判重的时间复杂度为 O ( 32 ! l o g ( 32 ! ) ) \mathcal{O}(32!log(32!)) O(32!log(32!))。
2.1.2 实现
#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<map>
using namespace std;
struct Node{
string str;
int step;
Node(string str="",int step=0):str(str),step(step){}
};
string ori(32,0),tar(32,0);
map<string,bool> match;
void read(){
for(int i=0;i<4;i++){
for(int j=1;j<8;j++){
int tmp;scanf("%d",&tmp);
if(tmp%10==1) ori[(tmp/10-1)*8]=tmp,ori[i*8+j]=0;
else ori[i*8+j]=tmp;
}
}
}
void mv(string& str,char val,int ind){
int fnd=0;
while(fnd<32&&str[fnd]!=val) fnd++;
if(fnd!=32) str[ind]=val,str[fnd]=0;
}
int BFS(){
queue<Node> que;
map<string,bool> vis;
Node start(ori);
que.push(start);
vis[start.str]=true;
while(!que.empty()){
Node cur=que.front();que.pop();
if(match[cur.str]) return cur.step;
for(int i=0;i<32;i++){
if(cur.str[i]==0){
Node nxt=cur;
mv(nxt.str,cur.str[i-1]+1,i);
if(!vis[nxt.str]){
vis[nxt.str]=true;
nxt.step=cur.step+1;
que.push(nxt);
}
}
}
}
return -1;
}
int main(){
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
tar[i*8+j]=(i+1)*10+(j+1);
}
}
match[tar]=true;
int T;scanf("%d",&T);
while(T--){
read();
printf("%d\n",BFS());
}
return 0;
}