Open the Lock HDU - 1195

普通bfs

题意:给两个四位数(1~9),求之间变换的最小步数

           1.每位数字可+1,10->1

           2.每位数字可-1,0->9

           3.相邻两位数字可交换,首尾不算相邻

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
int t;
char s1[5],s2[5];
struct node {
	int num[4],s;
}f,e;
bool book[15][15][15][15];
void bfs() {
	node a,b;
	f.s=0;
	a=f;
	book[a.num[0]][a.num[1]][a.num[2]][a.num[3]]=true;
	queue<node> q;
	q.push(a);
	while (!q.empty()) {
		a=q.front();
		q.pop();
		if (a.num[0]==e.num[0] && a.num[1]==e.num[1] && a.num[2]==e.num[2] && a.num[3]==e.num[3]) {
			printf ("%d\n",a.s);
			return;
		}
		for (int i=0;i<4;i++) {    //+1
			b=a;
			b.num[i]++;
			if (b.num[i]==10) b.num[i]=1;
			if (book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]==false) {
				book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]=true;
				b.s++;
				q.push(b);
			}
		}
		for (int i=0;i<4;i++) {     //-1
			b=a;
			b.num[i]--;
			if (b.num[i]==0) b.num[i]=9;
			if (book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]==false) {
				book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]=true;
				b.s++;
				q.push(b);
			}
		}
		for (int i=0;i<3;i++) {     //交换 
			b=a;
			b.num[i]=a.num[i+1];
			b.num[i+1]=a.num[i];
			if (book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]==false) {
				book[b.num[0]][b.num[1]][b.num[2]][b.num[3]]=true;
				b.s++;
				q.push(b);
			}
		}
	}
}
int main()
{
	scanf ("%d",&t);
	while (t--) {
		scanf ("%s%s",s1,s2);
		for (int i=0;i<4;i++) {
		    f.num[i]=s1[i]-'0';
			e.num[i]=s2[i]-'0';
		}
		memset(book,false,sizeof(book));
		bfs();
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值