将棋盘状态用一维数组表示
如下图,初始状态表示为 “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

最低0.47元/天 解锁文章
3016

被折叠的 条评论
为什么被折叠?



