历届试题 青蛙跳杯子 (BFS)

题目地址

青蛙跳杯子

解题思路

通过bfs来做这个题,每次判断一个和我们要的字符串是否相同。只要相同就直接输出当前的步数,因为bfs每个循环都会使得每一个状态的计数器加一,因此再往后找到的肯定比当前的步数多。需要剪枝的是可能会出现重复的字符串,这个时候就不要在放入队列中了,否则会超时的。

AC代码

#include <iostream>
#include <queue>
#include <map>

using namespace std;

struct node
{
	string s;
	int pos;
	int num;
	
	node()
	{
		s = "";
		pos = num = 0;
	}
	
	node(string ss, int pp, int nn)
	{
		s = ss;
		pos = pp;
		num = nn;
	}
};

int main()
{
	string s, t;
	int minnum = 0x3f3f3f3f;
	map<string, int> Map;
	
	cin >> s >> t;
	
	queue<node> que;
	struct node temp;
	int len = s.size();
	
	temp.s = s;
	
	for (int i=0; i<len; i++)
	{
		if (s[i] == '*')
		{
			temp.pos = i;
			break;
		}
	}
	
	que.push(temp);
	Map[s]++;
	
	while (!que.empty())
	{
		temp = que.front();
		que.pop();
		
		if (temp.s == t)
		{
			cout << temp.num << endl;
			return 0;
		}
		
		for (int i=-3; i<=3; i++)
		{
			int pos = temp.pos + i;
			string temps = temp.s;
			
			if (i == 0 || pos < 0 || pos >= len)
			{
				continue;
			}
			
			swap(temps[temp.pos], temps[pos]);
			
			if (!Map[temps])
			{
				que.push(node(temps, pos, temp.num+1));
				Map[temps] ++;
			}
		}
	}
	
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值