求大佬优化
查看原帖
求大佬优化
1036000
Ojld楼主2023/10/23 17:14

bfs ,但是会超时,求大佬帮我优化优化

#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;
string start,en;
int n;
const int N = 1010;
int bfs(string start){
    queue<string> q;
    unordered_map<string,int> d;
    q.push(start);
    d[start] = 0;
    while(q.size()){
        auto t = q.front();
        q.pop();
        if(t==en)return d[t];
        for(int i = 0 ;i < n ;i ++){
                int j = i + 1;
                auto x = t;
                if(x[i]=='*'){
                    x[i]='o';
                }
                else
                x[i] = '*';
                if(x[j]=='*'){
                    x[j]='o';
                }
                else
                x[j] = '*';
                if(!d[x]){
                    q.push(x);
                    d[x] = d[t] + 1;
                }
        }
    }
}
int main(){

    cin>>start;
    cin>>en;
    n = start.length();
    cout<<bfs(start)<<endl;
}
2023/10/23 17:14
加载中...