QQ联系我

BZOJ 1054: [HAOI2008]移动玩具

1054: [HAOI2008]移动玩具

Time Limit: 10 Sec  Memory Limit: 162 MB

Submit: 2483  Solved: 1380

[Submit][Status][Discuss]

Description

  在一个4*4的方框内摆放了若干个相同的玩具,某人想将这些玩具重新摆放成为他心中理想的状态,规定移动时只能将玩具向上下左右四个方向移动,并且移动的位置不能有玩具,请你用最少的移动次数将初始的玩具状态移动到某人心中的目标状态。

Input

  前4行表示玩具的初始状态,每行4个数字1或0,1表示方格中放置了玩具,0表示没有放置玩具。接着是一个空行。接下来4行表示玩具的目标状态,每行4个数字1或0,意义同上。

Output

  一个整数,所需要的最少移动次数。

Sample Input

1111
0000
1110
0010
1010
0101
1010
0101

Sample Output

4

题解

hash+bfs。

代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
const int N=(1<<20);
int step[N],vis[N],nx[10]={0,0,1,-1},ny[10]={1,-1,0,0};
struct map{
	char a[10][10];
}s,t;
int hash(map a){
	int temp=0,k=0;
	for(int i=1;i<=4;i++){
		for(int j=1;j<=4;j++){
			temp+=(a.a[i][j]-'0')*(1<<(k++));
		}
	}
	return temp;
}
queue<map>q;
void bfs(){
	int u=hash(s),v=hash(t);
	if(u==v){
		printf("0\n");
		return;
	}
	q.push(s);
	vis[u]=1;
	step[u]=0;
	int x,y,st,h;
	map a;
	while(!q.empty()){
		a=q.front();
		q.pop();
		st=step[hash(a)];
		for(int i=1;i<=4;i++){
			for(int j=1;j<=4;j++){
				for(int k=0;k<4;k++){
					x=i+nx[k],y=j+ny[k];
					if(x>=1&&x<=4&&y>=1&&y<=4){
						swap(a.a[i][j],a.a[x][y]);
						h=hash(a);
						if(!vis[h]){
							q.push(a);
							vis[h]=1;
							step[h]=st+1;
							if(h==v){
								printf("%d\n",step[h]);
								return;
							}
						}
						swap(a.a[i][j],a.a[x][y]);
					}
				}
			}
		}
	}
}
int main(){
	for(int i=1;i<=4;i++){
		scanf("%s",s.a[i]+1);
	}
	for(int i=1;i<=4;i++){
		scanf("%s",t.a[i]+1);
	}
	bfs();
	return 0;
}
posted @ 2017-10-25 16:35  czy020202  阅读(123)  评论(0编辑  收藏  举报