hdu1195 Open the Lock (BFS)

题意:给出两个4位的数字,都由1~9组成,要求经过一系列的操作将第一个数字变为第二个数字。操作有两种,

第一种:选择一位加上或减去1,9+1=1,1-1=9。

第二种:交换相邻的两位。第一位和第四位不相邻。


做法:简单bfs


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>

using namespace std;

struct Node{
	int stat;
	int step;
	Node() {}
	Node(int a, int b) : stat(a), step(b) {}
};

int T;
int start, end;
queue<Node> q;
int vis[11111];

void push(Node nex) {
	if (!vis[nex.stat]) {
		vis[nex.stat] = 1;
		q.push(nex);
	}
}

int bfs() {
	memset(vis, 0, sizeof(vis));
	while (!q.empty()) q.pop();
	Node e = Node(start, 0);
	vis[start] = 1;
	q.push(e);
	while (!q.empty()) {
		e = q.front();
		q.pop();
		if (e.stat == end) return e.step;
		Node nex;
		int a = e.stat / 1000;
		int b = e.stat % 1000 / 100;
		int c = e.stat % 100 / 10;
		int d = e.stat % 10;
		if (a == 9) nex = Node(e.stat - 8000, e.step + 1);
		else nex = Node(e.stat + 1000, e.step + 1);
		push(nex);
		if (a == 1) nex = Node(e.stat + 8000, e.step + 1);
		else nex = Node(e.stat - 1000, e.step + 1);
		push(nex);
		if (b == 9) nex = Node(e.stat - 800, e.step + 1);
		else nex = Node(e.stat + 100, e.step + 1);
		push(nex);
		if (b == 1) nex = Node(e.stat + 800, e.step + 1);
		else nex = Node(e.stat - 100, e.step + 1);
		push(nex);
		if (c == 9) nex = Node(e.stat - 80, e.step + 1);
		else nex = Node(e.stat + 10, e.step + 1);
		push(nex);
		if (c == 1) nex = Node(e.stat + 80, e.step + 1);
		else nex = Node(e.stat - 10, e.step + 1);
		push(nex);
		if (d == 9) nex = Node(e.stat - 8, e.step + 1);
		else nex = Node(e.stat + 1, e.step + 1);
		push(nex);
		if (d == 1) nex = Node(e.stat + 8, e.step + 1);
		else nex = Node(e.stat - 1, e.step + 1);
		push(nex);
		nex = Node(b * 1000 + a * 100 + c * 10 + d, e.step + 1);
		push(nex);
		nex = Node(a * 1000 + c * 100 + b * 10 + d, e.step + 1);
		push(nex);
		nex = Node(a * 1000 + b * 100 + d * 10 + c, e.step + 1);
		push(nex);
	}
	return 0;
}

int main() {
	scanf("%d", &T);
	while (T--) {
		scanf("%d%d", &start, &end);
		int ans = bfs();
		printf("%d\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值