题解 | #玛雅人的密码#
BFS搜索
set<string> visited;
int BFS(string str,string eam)
{
queue<pair<string, int> > myQueue;
myQueue.push(make_pair(str, 0));//压入初始点
visited.insert(str);
while (!myQueue.empty())
{
string curt = myQueue.front().first;//获取当前点
int t = myQueue.front().second;
myQueue.pop();
if (strstr(curt.c_str(), eam.c_str()))//满足规定值,退出
{
return t;
}
for (int i = 0; i < curt.size() - 1; i++)//状态变换
{
string next = curt;
swap(next[i], next[i + 1]);
if (visited.count(next))
{
continue;
}
myQueue.push(make_pair(next, t + 1));
visited.insert(next);
}
}
return -1;
}
凡岛公司福利 297人发布