八数码问题——回溯法

将棋盘状态用一维数组表示

如下图,初始状态表示为 “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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Daniel_26_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值