将棋盘状态用一维数组表示
如下图,初始状态表示为 “283164705”
算法思想:
使用回溯法。
按照当前布局进行DFS搜索,以当前布局是否出现过进行剪枝对象。
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<queue>
#include <iostream>
#include<stack>
using namespace std;
map<string,bool> state_record;//用于记录状态是否出现过
typedef struct
{
string num;//排列
int pos;//排列中空的位置
}node;
int depth=7;//限制搜索深度
int changeId[9][4]={{-1,-1,3,1},{-1,0,4,2},{-1,1,5,-1},
{0,-1,6,4},{1,3,7,5},{2,4,8,-1},
{3,-1,-1,7},{4,6,-1,8},{5,7,-1,-1}
};//0出现在0->8的位置后该和哪些位置交换
string des="123804765";
void swap(string &s,int a,int b)//交换字符串中的两个位置
{
char t=s[a];
s[a]=s[b];
s[b]=t;
}
void print(stack<node> res)//打印最后结果
{
string cur;//用于保存当前状态的字符串
stack<node> res1;
while(!res.empty())
{
node t=res.top();
res.pop();
res1.push(t);
}
while(!res1.empty ())
{
node t=res1.top();
res1.pop();
cur=t.num;
for(int i=0;i<9;i++)
{
if(cur[i]=='0')
cout<<" ";
else
cout<<cur[i]<<" ";
if((i+1)%3==0)
cout<<endl;
}
cout<<"→"<<endl;
}
}
void dfs(string n,int p,stack<node> res)
{
if(res.size()>=depth)
return;
node new_node;
new_node.num =n;
new_node.pos =p;
string cur=n;//用于保存当前状态的字符串
for(int i=0;i<4;i++)//扩展当前的状态,上下左右四个方向
{
int swapTo=changeId[new_node.pos][i];//将要和那个位置交换
if(swapTo!=-1)//-1则不交换
{
swap(cur,p,swapTo);//交换0的位置得到新状态
if(cur==des)//目标状态
{
stack<node> t;
t=res;
node t1;
t1.num =cur;
t.push(t1);
print(t);//打印目标状态
return;
}
if(state_record.count(cur)==0)//该状态未出现过,则将该状态入栈
{
state_record[cur]=1;
node n_node;
n_node.num =cur;
n_node.pos =swapTo;
res.push(n_node);
dfs(cur,swapTo,res);
res.pop();
}
swap(cur,p,swapTo);
}
}
return;
}
int main(){
string start;
int i=-1;
cin>>start;
while(start[++i]!='0');//查找初始状态0的位置
stack<node> res;
node new_node;
new_node.num =start;
new_node.pos =i;
res.push(new_node);
state_record[start]=1;
if(start!=des)//判断输入状态是否就是目的状态
dfs(start,i,res);
return 0;
}