hdu 1043 A*算法解决八数码问题

Eight

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23880    Accepted Submission(s): 6384
Special Judge


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  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
 

Source
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:   1044  1072  1180  1016  1067 





题意:给出3*3的方格,每个方格中有一个字母,且各不相同,来自于数字[0:8]或字母x,给出最快的操作序列使得排布变为[0:8],x

解法:A*算法,f=g+h,h为当前状态到目标状态的一个估计值,要<=实际花费值,g为当前实际花费步数,用优先队列对状态结点进行排序+用康托展开保存状态。



剪枝:在进行搜索之前,对除X之外的数列求逆序数,如果为奇数,那么不可能到达目标状态,因为目标状态的逆序值必定是偶数,而且每移动一步,当前状态除X之外的数列的逆序数不变。

原因是:
1.如果X和左边的数交换,那么数列本身不变(因为没有统计X),故逆序数自然不变。
2.如果X和上边的数交换:相当于把  ... a b c  ... 变成了...b c a ... ,那么必然可以忽略掉左右的省略号部分。

假如a比b、c都大,记f(x)为x左边比x大的个数。那么移动后f(a)不变,f(b)-1,f(c)-1,故逆序数奇偶性不变。

假如a比b、c都小,那么f(a)+2,逆序数奇偶性不变。

else,即假如a比其中一个大,比其中一个小,那么f(a)+1,还有一个f()-1,另外一个f()不变,故逆序数的奇偶性不变。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;


char s[50];
int b[9];

int ha[9]={1,1,2,6,24,120,720,5040,40320};  

char move_name[5]="udlr";

int dir[4][2]={{-1,0},{+1,0},{0,-1},{0,+1}};
struct Node
{
	int h,g,x,y,hash_num;
	int a[9];
	bool operator<(const Node c)const
	{
		return h+g>=c.h+c.g;
	}  

	int get_inverse()
	{
		
		int cnt=0;

		for(int i=0;i<9;i++)  if(a[i])
		{
			for(int j=0;j<i;j++) if(a[j]>a[i]) cnt++;
		}

		return cnt++;
	}
	int get_hash()
	{
		hash_num=0;

		for(int i=0;i<9;i++)  
		{
			int cnt=0;
			for(int j=0;j<i;j++)  if(a[j]>a[i])  cnt++;

			hash_num+=ha[i]*cnt;	
 		} 

		return hash_num;
	}

	int get_h()
	{
		h=0;
		for(int i=0;i<9;i++) if(a[i])
		{
			int px=(a[i]-1)/3,py=(a[i]-1)%3;
			h+=abs(px-i/3)+abs(py-i%3);
		}

		return h;
		
	}
	bool eq(Node c)
	{
		return hash_num==c.hash_num;
	}
}S,E;

const int maxn=4e5+4;
struct HSET
{
	int pre;
	char mov;
} hset[maxn];
bool vis[maxn];

bool in(int x,int y)
{
	return 0<=x&&x<=2&&0<=y&&y<=2;
}

int get_pos(int x,int y)
{
	return 3*x+y;
}

void print_ans(int ind)
{
	if(hset[ind].pre==-1) return;
	
	print_ans(hset[ind].pre);

	putchar(hset[ind].mov);

}
void Astar()
{

	if(S.eq(E)) return;
	

	priority_queue<Node>q;
	q.push(S);
	while(!q.empty())
	{
		Node nod=q.top();q.pop();
		int x=nod.x,y=nod.y;
		int pos=get_pos(x,y);


		for(int i=0;i<4;i++)
		{
			int tx=x+dir[i][0],ty=y+dir[i][1];
			if(!in(tx,ty))  continue;

			Node nex=nod;
			
			int tpos=get_pos(tx,ty);

			swap(nex.a[pos],nex.a[tpos]);
			int hsh=nex.get_hash();


			// printf("%d %d",hsh,nod.hash_num);
			if(vis[hsh])  continue;vis[hsh]=1;
			hset[hsh].pre=nod.hash_num;
			hset[hsh].mov=move_name[i];

			nex.x=tx,nex.y=ty;
			nex.g++;nex.get_h();
			

			if(nex.eq(E))
			{
				print_ans(hsh);
				return;
			}

			q.push(nex);


		}


	}

}
int main()
{
	for(int i=0;i<8;i++) E.a[i]=i+1;
	E.a[8]=0;
	E.x=E.y=2;
	E.get_hash();


	while(gets(s))
	{
		memset(vis,0,sizeof vis);

		int len=strlen(s);
		int k=0;
		for(int i=0;i<len;i++)
		{
			if(s[i]==' ')  continue;
			if(s[i]=='x')  {S.a[k]=0; S.x=k/3; S.y=k%3; k++; }
			else    S.a[k++]=s[i]-'0';
		}
		S.g=0;S.get_h();
		
		// for(int i=0;i<9;i++)  printf("%d ",S.a[i]);

		int ivs=S.get_inverse();
		if(ivs&1)
		{
			puts("unsolvable");
			continue;
		}
		int hsh=S.get_hash();
		hset[hsh].pre=-1;
		vis[hsh]=1;

		Astar();
		putchar('\n');

	}
	return 0;
}


include using namespace std; struct node{ int nodesun[4][4]; int pre; //上一步在队列中的位置 int flag ; //步数标识,表示当前的步数为有效的 int value; //与目标的差距 int x,y; //空格坐标 }queue[1000]; //移动方向数组 int zx[4]={-1,0,1,0}; int zy[4]={0,-1,0,1}; //当前步数 int top; int desti[4][4];//目标状态 int detect(struct node *p)//检查是否找到 {int i,j; for(i=1;i<4;i++) for(j=1;jnodesun[i][j]!=desti[i][j]) return 0; return 1; } //打印 void printlj() {int tempt; int i,j; tempt=top; while(tempt!=0) { for(i=1;i<4;i++) for(j=1;j<4;j++) {cout<<queue[tempt].nodesun[i][j]; if(j==3) cout<<" "<<endl; } tempt=queue[tempt].pre; } } //现在状态目标状态有多少个不同位置 int VALUE(struct node *p) {int count=0; int i,j; for(i=1;i<4;i++) for(j=1;jnodesun[i][j]!=desti[i][j]) count++; return count; } void main() { //初始化 int i,j,m,n,f; int min=10; int temp,find=0,minnumber; top=1; for(i=1;i<4;i++) for(j=1;j<4;j++) {cout<<"请输入第"<<i<<"行"<<"第"<<j<<"列的值"<>temp; queue[1].nodesun[i][j]=temp; } cout<<"请输入初始状态的空格的位置(行)"<>temp; queue[1].x=temp; cout<<"请输入初始状态的空格的位置(列)"<>temp; queue[1].y=temp; queue[1].value=VALUE(&queue[1]); queue[1].pre=0; //上一步在队列中的位置 queue[1].flag=0; //目标状态 for(i=1;i<4;i++) for(j=1;j<4;j++) {cout<<"请输入目标状态第"<<i<<"行"<<"第"<<j<<"列的值"<>temp; desti[i][j]=temp; } //根据估价函数 while(!find&&top>0) { for(i=1;i<=top;i++) //////////////////////////////////////////// //min为上一图中与目标图有多少个元素不相同,queue[i]为当前图与目标图有多少个元素不相同通过这两个数的比较,就可以得出当前图较之上一图向目标图接近同时把当前的i记录下来进行下一步比较 {if(queue[i].value<min&&queue[i].flag==0) {minnumber=i;// min=queue[i].value; //还有多少不同的位数 } } queue[minnumber].flag=1; //表示此位有效 ////////////////////////////////////// // for(f=0;f=1&&i=1&&j<=3) {top++; ///////////////////////////////////////////// //位置交换 queue[top]=queue[minnumber]; queue[top].nodesun[m][n]=queue[minnumber].nodesun[i][j]; queue[top].nodesun[i][j]=0; /////////////////////////////////////// //空格移动方向 queue[top].x=i; queue[top].y=j; /////////////////////////////////////// queue[top].pre=minnumber; //上一步在队列中的位置 queue[top].value=VALUE(&queue[top]); //有多少位与目标不同 queue[top].flag=0; //标识位初始化 if(detect(&queue[top])) //检查是否为目标 {printlj(); //打印 find=1; //设找到标识位 break; } } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值