题目地址
解题思路
通过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;
}