欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【 POJ - 1077 】 H - Eight (八数码问题) 【 BFS + hash判重 】

程序员文章站 2022-07-07 10:40:10
...

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 x

where 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 a description of a configuration of the 8 puzzle. The 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.

Sample Input

 2  3  4  1  5  x  7  6  8 

Sample Output

ullddrurdllurdruldr

思路:

用二维数组记录下每种情况的状态图,总情况为9!= 362880。八数码问题最主要是判重,开始用的set判重,但是超时了,然后改为hash表判重

八数码问题也可以参考一下这篇(set判重):八数码


代码:

#include<iostream>
#include<set> 
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
typedef int state[9];
const int maxn=362900; //情况数
const int hashsize=1000003;
int head[hashsize],nexth[hashsize]; //表头,后继
state st[maxn],goal={1,2,3,4,5,6,7,8,0};  //st状态数组,goal目标九宫格
int last[maxn];  //记录上一步
int dx[]={-1,1,0,0};  //四个方向
int dy[]={0,0,1,-1};
char op[maxn];
set<int> s;

char dire(int x,int y)  //确定方向
{
	if(x==1 && y==0) return 'd';
	else if(x==-1 && y==0) return 'u';
	else if(x==0 && y==1) return 'r';
	else if(x==0 && y==-1)return 'l';
}

int myhash(state &s)  
{
	int num=0;
	for(int i=0;i<9;i++) num = num*10+s[i]; //将状态图转为9位数
	return num%hashsize; 
}

int try_insert(int rear)  //尝试插入
{
	int h=myhash(st[rear]); 
	int u=head[h]; //h所在表的头u
	while(u)
	{
		if(memcmp(st[rear],st[u],sizeof(st[u]))==0) return 0; //不能插
		u=nexth[u]; //后继
	}
	nexth[rear]=head[h]; //头插
	head[h]=rear;
	return 1;
}

int bfs()
{
	fill(head,head+hashsize,0);
	int front=1,rear=2;
	while(front<rear)
	{
		state &f = st[front]; 队头状态
		if(memcmp(goal,f,sizeof(f))==0)  return front; //与目标同,返回

		int z=0;
		for(;z<9;z++) if(!f[z]) break;  //在状态数组中找到0的位置
		int nowx=z/3,nowy=z%3;  //0的行列位置
		for(int i=0;i<4;i++)
		{
			int newx=nowx+dx[i]; //下一步的x,y
			int newy=nowy+dy[i];
			int newz=newx*3+newy; //确定在状态数组中的位置
			if(newx>=0 && newx<3 && newy>=0 && newy<3) //在范围内
			{
				state &r=st[rear]; //队尾的位置
				memcpy(r,f,sizeof(f)); //先把上一步的状态复制给下一步
				r[newz]=f[z]; //然后交换两个位置,实现移动
				r[z]=f[newz];
				op[rear]=dire(dx[i],dy[i]); //记录该步的方向
				last[rear]=front;  //记录该步的上一步
				if(try_insert(rear)) rear++; //插入成功,队尾往后一步
			}	
		}
		front++; //队头可以走的下一步都记录下来了,front++相当于出队
	} 
	return -1; //找不到
}

int main()
{
	char c;
	for(int i=0;i<9;i++)
	{
		cin>>c;
		if(c=='x') st[1][i]=0;  //将x看作0
		else st[1][i]=c-'0';  
	}
	int ans=bfs();
	if(ans==-1) cout<<"unsolvable"<<endl;
	else 
	{
		string ss;  //记录步骤
		while(ans!=1) 
		{
		    ss += op[ans];
		    ans=last[ans];
		}
		reverse(ss.begin(),ss.end()); //记录的步骤是反的,要翻转
		printf("%s\n",ss.c_str());
	}
	return 0;
}

【 POJ - 1077 】 H - Eight (八数码问题) 【 BFS + hash判重 】