题解 | #玛雅人的密码#

玛雅人的密码

https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0

#include <iostream>
#include <map>
#include <queue>
using namespace std;
map<string, bool> visited;
queue<pair<string, int>> q;//队列元素是对组,first是字符串,second是由初始字符串经过多少步所得
pair<string, int> father, child;
string t;
void bfs(string s,int step)
{
	//将爸爸入队
	father.first = s;
	father.second = step;
	q.push(father);
	//只要队列不空
	while (!q.empty())
	{
		//将爸爸出队
		father = q.front();
		q.pop();
		//如果爸爸就是目标字符串,又由于是BFS,其所得步骤一定最少,返回结果即可
		if (father.first.find("2012") != string::npos)
		{
			//队列元素是对组,first是字符串,second是由初始字符串经过多少步所得
			cout << father.second;
			return;
		}
		//如果爸爸没被访问过,就访问,下次遇到就不要入队,避免重复,要保证BFS树每个节点都互异
		if (visited[father.first] == 0)
		{
			visited[father.first] = 1;
			//挨个检查自己的儿子符不符合要求
			for (int i = 0; i < s.length() - 1; i++)
			{
				t = father.first;
				swap(t[i], t[i + 1]);
				if (visited[t]==0)
				{//符合要求的儿子挨个入队
					child.first = t;
					child.second= father.second+1;
					q.push(child);
				}
			}
		}
	}
}
int main()
{
	int N;
	cin >> N;
	string s;
	cin >> s;
	bfs(s,0);
}

全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务