题目大意:给出八个数和一个x(代表零),问是否可以通过交换零和其它数字的位置到达最终状态
思路:用广搜扩展目的状态所能到达的所有状态,然后直接判断,这个题目我用了map标记,HDU上会超时,把map改成康托展开,或者直接用IDA*算法应该就可以了
#include <stdio.h>
#include <string.h>
#include <queue>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <map>
using namespace std;
map<string,int> mm; // 用map映射所有能够到达的状态
char ss[10];
int dir[4][2] = {-1,0, 0,-1, 0,1, 1,0}; // 上,左,右,下
char cc[6] ="ulrd"; // 空格移动的四个方向对应移动的四个方向 上0, 左1, 下2, 右3;
struct ak
{
char ch[10]; // 结构体中表示当前状态的数组
int x, y; // 空格所在坐标
int front; // 前驱下标
int arr; // 当前下标
int where; // 方向
}temp, temp2, gg[400000];
queue<ak> qq; // 结构体变量存入队列qq中
void gao(int x) // 类似于递归,输出该点的方向,通过该点的前驱递归,直到最后一个
{
if(x == 0) // 递归结束条件
{
return ;
}
printf("%c", cc[gg[x].where]);
gao(gg[x].front);
}
void bfs()
{
int cnt = 0; // map中存扩展状态字符串的映射数字
while(!qq.empty())
{
temp = qq.front();
qq.pop();
for(int i = 0; i < 4; i++)
{
temp2 = temp;
temp2.x = temp.x + dir[i][0];
temp2.y = temp.y + dir[i][1];
if(temp2.x >= 0 && temp2.x < 3 && temp2.y >= 0 && temp2.y < 3)
{
swap(temp2.ch[temp2.x*3 + temp2.y ], temp2.ch[temp.x*3 + temp.y ]); // 表示从第几个格子换到第几个格子中temp是temp2的上一步
// temp代表空格,temp2代表空格的新位置
if(mm.find(temp2.ch) == mm.end())
{
gg[++cnt].where = 3-i; //为什么是3-i? 因为是倒着推,所以方向相反,cnt是map映照容器中的数字映照,每有一个新状态就存入map
//3-i 是对应cc里的方向的下标表示
gg[cnt].x = temp2.x; //存当前状态的空格所在坐标
gg[cnt].y = temp2.y; //存当前状态的空格所在坐标
strcpy(gg[cnt].ch,temp2.ch); //将当前数组位置状态入队到结构体数组中
gg[cnt].front = temp.arr; //存结构体的前驱下标
gg[cnt].arr = cnt; //存结构体的当前下标
qq.push(gg[cnt]); //当前状态入队
mm[temp2.ch] = cnt; //当前状态存入map
}
}
}
}
}
int main()
{
char tempch[1000];
int len;
mm["12345678x"] = 0; // 最终状态,用map数组映射为0
strcpy(gg[0].ch, "12345678x"); // 将初始状态存入结构体的表示当前状态的数组中去
gg[0].arr = 0;
gg[0].x = 2; // 为什么gg[0].x 和gg[0].y 是从2开始?
gg[0].y = 2; // 因为开始的扩展是从要达到的状态扩展的,右下角是x即空格的位置,坐标为2,2;
qq.push(gg[0]);
bfs();
while(gets(tempch))
{
int len = strlen(tempch);
int con = 0;
for(int i = 0; i < len; i++)
{
if((tempch[i] >= '0' && tempch[i] <= '9') || tempch[i] == 'x')
{
ss[con++] = tempch[i]; // 输入的状态,也就是要找的是否存入map中的状态
}
}
ss[con] = '\0'; // 不能省略
if(mm.find(ss) != mm.end()) // map中的find函数判断,如果输入的位置状态在map中可以找到
{ //(已经通过bfs把可到达状态全部拓展并存入map中)
gao(mm[ss]); // 通过当前位置映照的数字,把已经存好的结果输出来
}
else
{
printf("unsolvable");
}
puts("");
}
return 0;
}