八数码(POJ-1077或HDU-1043)

    Eight

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, 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  8
Sample Output
ullddrurdllurdruldr


神奇的八数码,崩溃了老长时间,要着好这道题真不容易,先要学好以下的推荐知识。
最重要的是A*算法,f = g + h,其中g为已花费的代价,h为剩余代价,A*算法的详细介绍可以参考这篇博客A*算法
这里我们只用到了其中的皮毛,里面还有好多学问值得我们学习。
<1> : 康托展开,在这里推荐一篇极好的博客:康托展开
<2> : 曼哈顿距离,这个很好理解,在平面直角坐标系中设点(x1,y1),(x2,y2),那么这两个点之间的
曼哈顿距离=abs(x1-x2)  + abs(y1-y2)。
<3> : 哈希问题,这里我们用康托展开来判重。
<4> : 判断是否有解,根据逆序数直接判断有无解,对于一个八数码,依次排列之后,每次是将空位和相邻位进行调换,研究后会发现,每次调换,逆序数增幅都为偶数,也就是不改变奇偶性,因为最终状态12345678的逆序数为零,所以只有初始状态的逆序数为偶数才有解
至于优先队列的排序规则,这里采用的是先h后g,当然还有很多种选择,只不过这种的更省时,当然我们也可以实验一下其他的。
这里附上八数码八境界,可以提高一下我们自己,本人的代码只在第六境界中徘徊,还是菜啊。

这里提醒一下,标准的结果不止一种,为此我还郁闷了很长时间。具体原因可能是因为bfs的时候上下左右走的顺序不一样。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cmath> 
using namespace std;
struct node{
	int op[9];
	int x;
	int g,h;
	int hash;
	bool operator <(node c)const
	{
		if(c.h==h)
		return g>c.g;
		else
		return h>c.h;
	}
};
int hash_op[9] = {1,1,2,6,24,120,720,5040,40320};//存储的阶乘,可以直接使用,省时。
int nex_t[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
char nexx[5] = "rldu";
char lu[700000];
int pre[700000];
int vis[700000];
int get_hash(int a[9])
{
  int sum = 0;
  for(int i=0;i<9;i++)
  {
  	int k = 0; 
	for(int j=i;j<9;j++)
	if(a[i]>a[j])k++;
	sum += k*hash_op[9-i-1]; 
  }	
  return sum;
}
int get_h(int a[9])
{
   int ans = 0;
   for(int i=0;i<9;i++)
   {
	  int xx = (a[i]-1)/3; //为什么要减掉1,因为这里xx保存的是a[i]最终应该在第几行,位于(0,0)位置的数是1而不是0
   	  int yy = (a[i]-1)%3; // 同上
   	  if(a[i]==0)xx = 2,yy = 2;//最终状态0位于第2行,第2列
   	  ans += abs(xx-i/3) + abs(yy - i%3);// i/3 存储的是a[i]现在在第几行,i%3存储的是a[i]现在在第几列。这里不要搞混了,想要更明白的话专辑举个例子试验一下,俺智商低,就是这么办的。
   }
   return ans;
}
bool isok(int a[9])
{
  int sum = 0;
  for(int i=0;i<9;i++)
  {
    for(int j=i;j<9;j++)
	{
	  if(a[i]>a[j]&&a[i]&&a[j]) sum++;//求逆序数的时候不要加上了0,这里不要大意。
    }	
 }
  if(sum%2==0)return true;
  return false;	
} 
priority_queue<node> pp;
node cur,now;
int main()
{
   char q[50];
   int pos;
   int en[9]={1,2,3,4,5,6,7,8,0};
   int cur_op[9];
   while(gets(q)!=NULL)
   {
      memset(vis,0,sizeof(vis));
      memset(pre,0,sizeof(pre));
      memset(lu,'\0',sizeof(lu));
      while(!pp.empty())pp.pop();//一定不要忘了清空队列
      int k= 0;
      for(int i=0;i<strlen(q);i++)
	  {
	    if(q[i]==' ')continue;
		if(q[i]=='x'){pos=k;cur_op[k]=0;}
		else cur_op[k] = q[i] - '0';
		k++;	
	  } 

   	  memcpy(&cur.op,cur_op,sizeof(cur_op));
   	  cur.g = cur.h = 0;
   	  cur.x=pos;
   	  
   	  int tmp_t = get_hash(cur_op);
	  cur.hash=tmp_t;
	  vis[tmp_t] = 1;
	  pre[tmp_t] = 0;
	  if(!isok(cur_op))
	  {
	  	printf("unsolvable\n");
	  }
	  else
	  {
	  	pp.push(cur);
	  	int num = 0;
	  	//pre[0] = -1;
	  	while(!pp.empty())
        {
          cur = pp.top();pp.pop();
		  if(cur.hash==46233) // 其中46233为最终状态的哈希值 
		  {
		   //printf("可以\n");
		    break;
		  }
		  for(int i=0;i<4;i++)
		  {
			int xx = cur.x / 3 + nex_t[i][0];
		  	int yy = cur.x % 3 + nex_t[i][1];
		  	if(!(xx>=0&&xx<3&&yy>=0&&yy<3))continue;
		    memcpy(&now.op,&cur.op,sizeof(cur.op));
		    swap(now.op[cur.x],now.op[xx*3+yy]);

		    int p = get_hash(now.op);
		    if(vis[p]!=0)continue;
		    now.hash = p;vis[p]=1;now.x = xx*3+yy;now.g = cur.g + 1;
		    now.h = get_h(now.op);
		    pre[p] = cur.hash;
			lu[p] = nexx[i];
			pp.push(now); 
		  }
		}
		pos = cur.hash;
		//printf("%d\n",pos);
		char c[700000];
		memset(c,'\0',sizeof(c));
		int k=0;
		while(pre[pos]!=0)
		{
		  c[k] = lu[pos];
		  pos = pre[pos];
		  k++;	
	    }
	    for(int i=k-1;i>=0;i--)printf("%c",c[i]);
		printf("\n"); 
	 }
    }
	return 0; 
} 

水波,借鉴了部分学长的博客。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值