广搜做法,MLE了,看看要怎么优化
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node{
string str;
int step;
node(string a, int b) {
str = a;
step = b;
}
};
string A, B;
queue<node> Q;
int bfs() {
Q.push(node(A, 0));
while(!Q.empty()) {
node cur = Q.front();
Q.pop();
for(int i = 0; i < cur.str.length() - 1; i ++) {
string s = cur.str;
if(s[i] == '*') s[i] = 'o';
else s[i] = '*';
if(s[i + 1] == '*') s[i + 1] = 'o';
else s[i + 1] = '*';
Q.push(node(s, cur.step + 1));
if(s == B) {
return cur.step + 1;
}
}
}
return 0;
}
int main(){
cin >> A >> B;
cout << bfs();
return 0;
}