杭电OJ 1195(C++)

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

char start[5], password[5]; //起始密码,正确密码
int vis[10000]; //每个四位数的访问情况

struct node
{
	char str[5]; //密码
	int step; //操作次数
};

//广搜
void BFS()
{
	queue<node> Q;
	node q;
	strcpy(q.str, start);
	q.step = 0;
	Q.push(q);
	while (!Q.empty())
	{
		q = Q.front();
		Q.pop();
		if (strcmp(q.str, password) == 0)
		{
			cout << q.step << endl;
			return;
		}
		//将某一位加1
		for (int i = 0; i < 4; i++)
		{
			node p = q;
			if (p.str[i] == '9')
				p.str[i] = '1';
			else
				p.str[i] += 1;

			p.step++;
			int temp;
			//将字符串转换为整型
			sscanf(p.str, "%d", &temp);
			if (!vis[temp])
			{
				vis[temp] = 1;
				Q.push(p);
			}
		}
		//将某一位减1
		for (int i = 0; i < 4; i++)
		{
			node p = q;
			if (p.str[i] == '1')
				p.str[i] = '9';
			else
				p.str[i] -= 1;
			p.step++;
			int temp;
			sscanf(p.str, "%d", &temp);
			if (!vis[temp])
			{
				vis[temp] = 1;
				Q.push(p);
			}
		}
		//交换相邻两位
		for (int i = 0; i < 3; i++)
		{
			node p = q;
			char t;
			t = p.str[i];
			p.str[i] = p.str[i + 1];
			p.str[i + 1] = t;
			p.step++;
			int temp;
			sscanf(p.str, "%d", &temp);
			if (!vis[temp])
			{
				vis[temp] = 1;
				Q.push(p);
			}
		}
	}
}

int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		cin >> start >> password;
		memset(vis, 0, sizeof(vis));
		BFS();
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值