
八数码问题是bfs中的经典问题,经常也会遇到与其相似的题目。用到的思想是bfs+hash;主要是由于状态分散,无法直接用一个确定的数表示。所以导致bfs时,无法去判断一个状态是否已经被搜过。也无法用d数组去求解。这个时候就需要用到hash的方法判断当前状态是否已经被搜过。并按照搜索的顺序给每个状态编号(用这个编号代替对应的状态,与状态一一对应,为了求d[]),将所有的状态存起来,供hash查找。
值得注意的是,八数码问题的状态正好是所有的全排列(9!),由于这个特殊的原因,可以直接用每个状态对应的是第几个排列来给状态编号。这样的一一对应,可以做到当给定一个状态时,就能过直接计算出这个状态对应的编号,这样就可以直接用一个数组标记这个状态是否被搜索过,就不需要利用哈希技术来查找这个状态是否已经被搜过。
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1043
Problem Description
The 15-puzzle has been around for over 100 years; even if you don't know it by that name, you've seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let's call the missing tile 'x'; the object of the puzzle is to arrange the tiles so that they are ordered as:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 xwhere the only legal operation is to exchange 'x' with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12
13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x
r-> d-> r->The letters in the previous row indicate which neighbor of the 'x' tile is swapped with the 'x' tile at each step; legal values are 'r','l','u' and 'd', for right, left, up, and down, respectively. Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing 'x' tile, of course). In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three arrangement.
Input
You will receive, several descriptions of configuration of the 8 puzzle. One description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus 'x'. For example, this puzzle 1 2 3 x 4 6 7 5 8 is described by this list: 1 2 3 x 4 6 7 5 8
Output
You will print to standard output either the word ``unsolvable'', if the puzzle has no solution, or a string consisting entirely of the letters 'r', 'l', 'u' and 'd' that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line. Do not print a blank line between cases.
Sample Input
2 3 4 1 5 x 7 6 8Sample Output
ullddrurdllurdruldr代码G++(需要使用queue队列结构):耗时68ms
说明:本解法最精彩的地方在于hash值的计算,整体思路非常简单,倒推算出所有的hash。
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
//简要记录步信息
typedef struct Step_s
{
//上一步到这一步的方向
char dir;
//上一步的hash值
int parent;
} Step;
//倒推步法时记录的队列节点
typedef struct Node_s
{
//魔板信息
int board[9];
//x所在位置
int x_index;
//下一步的hash值
int child;
} Node;
//四个方向
int dir[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
//用于hash值计算
int fac[10];
//所有步法集合
Step step_set[370000];
//设置阶乘值,用于后面的hash值计算
void set_fac()
{
fac[0] = 1;
for (int i = 1; i <= 8; ++i) {
fac[i] = fac[i - 1] * i;
}
}
//对于任意的board,算出对应的hash值
int board_hash(int board[])
{
int i, j, ans = 0, k;
for (i = 0; i < 9; ++i) {
k = 0;
for (j = i + 1; j < 9; j++) {
if (board[i] > board[j]) {
k++;
}
}
ans += k * fac[8 - i];
}
return ans;
}
//广度优先搜索
void bfs(int finish[])
{
queue<Node> Q;
Node current;
int tx, ty, temp, t = 0;
//记录这个节点的魔板信息
for (int i = 0; i < 9; ++i) {
current.board[i] = finish[i];
}
//x在current.board[8]的位置上,child和parent的0表示结束和存在路径
current.x_index = 8; current.child = 0;
step_set[current.child].parent = 0;
Q.push(current);
while (!Q.empty())
{
//取得队列的第一个元素
current = Q.front(); Q.pop();
//从4个方向开始前进
for (int i = 0; i < 4; ++i) {
Node next = current;
//取得该方向的下一个位置
tx = current.x_index % 3 + dir[i][0];
ty = current.x_index / 3 + dir[i][1];
//防止出界
if (tx >= 0 && ty >= 0 && tx < 3 && ty < 3) {
next.x_index = ty * 3 + tx;
//交换x的位置
temp = next.board[next.x_index];
next.board[next.x_index] = next.board[current.x_index];
next.board[current.x_index] = temp;
//计算hash值
next.child = board_hash(next.board);
//查看是否重复
if (step_set[next.child].parent == -1) {
//上一步的hash值
step_set[next.child].parent = current.child;
//设置方向
if (i == 0)step_set[next.child].dir = 'l';
if (i == 1)step_set[next.child].dir = 'r';
if (i == 2)step_set[next.child].dir = 'u';
if (i == 3)step_set[next.child].dir = 'd';
//每次前进则放进队列(广度优先搜索)
Q.push(next);
}
}
}
}
}
int main()
{
int i, j, s, board_input[10], finish[9];
char ch[50];
/*完成状态是[1,2,3,4,5,6,7,8,9]*/
for (i = 0; i < 9; ++i) {
finish[i] = i + 1;
}
//初始化步数集合的父hash值
for (i = 0; i < 370000; ++i) {
step_set[i].parent = -1;
}
//设置阶乘函数,用于后面的hash值计算
set_fac();
//开始倒推,设置所有的步法
bfs(finish);
//输入魔板,gets函数能够输入整行
while (gets(ch)) {
for (i = 0, j = 0; ch[i] != '\0'; i++) {
if (ch[i] == 'x') {
board_input[j++] = 9;
}
else if (ch[i] >= '0' && ch[i] <= '8') {
board_input[j++] = ch[i] - '0';
}
}
//计算输入的魔板hash值
s = board_hash(board_input);
//如果不存在到达这种魔板的路线
if (step_set[s].parent == -1) {
printf("unsolvable\n");
continue;
}
//输出所有的步法
while (s != 0) {
printf("%c", step_set[s].dir);
s = step_set[s].parent;
}
printf("\n");
}
}