11111

· · 题解

看题解区没有状压 bfs,就来一发。

大体思路是这样的,题目要求搜出能否在六步之内到达全开的状态。我们就可以反过来搜,搜索出全开的状态,能在六步之内到达的所有状态。把这些答案用 map 存起来。这样能在每次询问的时候用 \mathcal O(1) 的复杂度。得出答案了。

#include<bits/stdc++.h>
using namespace std;
unordered_map<string,int> mp;
queue<string> q;
char dff(char s){
    if(s=='1'){
        return '0';
    }
    return '1';
}
void bfs(){
    q.push(" 1111111111111111111111111");
    mp[" 1111111111111111111111111"]=0;
    while(!q.empty()){
        string p=q.front();
        q.pop();
        if(mp[p]<6){
            string s;
            s=p;
            for(int i=1;i<=25;i++){
                s=p;
                s[i]=dff(s[i]);
                if(i+5<=25){
                    s[i+5]=dff(s[i+5]);
                }
                if(i-5>=1){
                    s[i-5]=dff(s[i-5]);
                }
                if(i%5!=1){
                    s[i-1]=dff(s[i-1]);
                }
                if(i%5!=0){
                    s[i+1]=dff(s[i+1]);
                }   
                if(mp[s]==0){
                    q.push(s);
                    mp[s]=mp[p]+1;
                }
            }

        }
    }
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t;
    bfs();
    while(t--){
        string asd,s=" ";
        for(int i=1;i<=5;i++){
            cin>>asd;
            s+=asd;
        }
        if(s==" 1111111111111111111111111"){
            cout<<"0\n";
        }
        else if(mp[s]!=0){
            cout<<mp[s]<<"\n";
        }
        else{
            cout<<"-1\n";
        }
    }
    return 0;
}