有9只盘子,排成1个圆圈。
其中8只盘子内装着8只蚱蜢,有一个是空盘。
我们把这些蚱蜢顺时针编号为 1~8
每只蚱蜢都可以跳到相邻的空盘中,
也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。
请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列,
并且保持空盘的位置不变(也就是1-8换位,2-7换位,…),至少要经过多少次跳跃?
简要分析
这道题广度优先搜索和深度优先搜索均可实现,但是这道题需要求出最短步数,所以显然广度优先搜索能更快的达到目标(因为第一个结果即为所求答案)
并且深度搜索容易进入死循环!!
#include<iostream>
#include<queue>
#include<string>
#include<map>
using namespace std;
const string st="012345678";
const string ed="087654321";
queue<pair<pair<string,int>,int> > que;//从左到右依次为:当前各位置的蚂蚱编号、空位位置、当前步数
const int d[5]={1,2,7,8};
map<string,string> parent;//记录当前状态的前一个状态
int main()
{
int ans;
parent[st]="";
que.push(make_pair(make_pair(st,0),0));
while(!que.empty())
{
string temstr=que.front().first.first;
int tempos=que.front().first.second;
int temcou=que.front().second;
if(temstr==ed)
{
ans=temcou;
break;
}
que.pop();
for(int i=0;i<4;i++)
{
string y=temstr;
swap(y[tempos],y[(tempos+d[i])%9]);
if(parent.count(y)==0)//返回指定元素出现的次数
{
parent[y]=temstr;
que.push(make_pair(make_pair(y,(tempos+d[i])%9),temcou+1));
}
}
}
cout<<ans;
//打印路径
for (string now = ed; now != ""; now = parent[now]) {
printf("%s\n", now.c_str());
}
}
通过广度优先搜索解决蚱蜢在圆圈盘子上重新排列的问题,寻找最少的跳跃次数以改变其排列顺序。
391

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



