wikioi p1225 八数码难题

数据弱,没加优化都过了。

dfs和bfs的题目我就不多说了,就是繁杂的模拟。

错了的话都是小问题。

#include<stdio.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<stdlib.h>
using namespace std;
const int max_n = 3628810;
const int max_r = 4;
bool f[max_n];
struct node
{
	int m[4][4];
	int x,y;
	int c;
}now,next; 
int ans[max_r][max_r];
queue <struct node> Q; //123804765
int re(struct node t)
{
	int ans=0;
	int i,j;
	int u=1;
	int v=2;
	for (i=1;i<=3;i++)
	for (j=1;j<=3;j++)
	{
		ans+=u*t.m[i][j];
		u*=v;
		v++;
	}
	return ans;
} 
int init()
{
	int i,j;
	char c;
	for (i=1;i<max_r;i++)
	for (j=1;j<max_r;j++)
	{
		scanf("%c",&c);
		ans[i][j]=c-'0';
	}
	now.m[1][1]=1;
	now.m[1][2]=2;
	now.m[1][3]=3;
	now.m[2][1]=8;
	now.m[2][2]=0;
	now.m[2][3]=4;
	now.m[3][1]=7;
	now.m[3][2]=6;
	now.m[3][3]=5;
	now.x=2;
	now.y=2;
	now.c=0;
	Q.push(now);
}
bool r(struct node t)
{
	int i,j;
	for (i=1;i<max_r;i++)
	for (j=1;j<max_r;j++)
	if (ans[i][j]!=t.m[i][j]) return false;
	return true;
}
int work_put()
{
	while (!Q.empty())
	{
		now=Q.front();
		Q.pop();
		if (r(now)) {printf("%d",now.c);return 0;}
		int x,y;
		x=now.x;
		y=now.y;
		if (x>1)
		{
			next=now;
			next.c=now.c+1;
			swap(next.m[x-1][y],next.m[x][y]);
			next.x--;
			if (!f[re(next)])
			{
			f[re(next)]=true;
			Q.push(next); 
			}
		} 
		if (x<3)
		{
			next=now;
			next.c=now.c+1;
			swap(next.m[x+1][y],next.m[x][y]);
			next.x++;
			if (!f[re(next)]){
			f[re(next)]=true;
			Q.push(next); }
		} 
		if (y>1)
		{
			next=now;
			next.c=now.c+1;
			swap(next.m[x][y-1],next.m[x][y]);
			next.y--;
			if (!f[re(next)]){
			f[re(next)]=true;
			Q.push(next); }
		} 
		if (y<3)
		{
			next=now;
			next.c=now.c+1;
			swap(next.m[x][y+1],next.m[x][y]);
			next.y++;
			if (!f[re(next)]) 
			{
			f[re(next)]=true;
			Q.push(next); 
			} 
		} 
	}
}
int main()
{
	init();
	work_put();
	return 0;
} 


 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值