1 solutions

  • 0
    @ 2023-10-18 10:01:22

    C++ :

    #include<bits/stdc++.h>
    using namespace std;
    map<string,int> dist;
    map<string,pair<char,string> > pre; //pre[a]={'op',b} 表示a的上一步是b,且由op操作过来的 
    /*
    0 1 2 3 
    7 6 5 4
    */
    string mv0(string s) //第一种移动 
    {
        swap(s[0],s[7]);
        swap(s[1],s[6]);
        swap(s[2],s[5]);
        swap(s[3],s[4]);
        return s;
    }
    string mv1(string s) //第二种移动 
    {
        char c=s[3];
        s[3]=s[2],s[2]=s[1],s[1]=s[0],s[0]=c;
        c=s[4];
        s[4]=s[5],s[5]=s[6],s[6]=s[7],s[7]=c;
        return s;
    }
    string mv2(string s) //第三种移动 
    {
        char c=s[1];
        s[1]=s[6],s[6]=s[5],s[5]=s[2],s[2]=c;
        return s;
    }
    int bfs(string start,string end)
    {
        queue<string> q;
        dist[start]=0;
        q.push(start);
        while(q.size())
        {
            string t=q.front();
            q.pop();
            if(t==end) //找到终点 
            {
                return dist[end];
            }
            string m[3];
            m[0]=mv0(t);
            m[1]=mv1(t);
            m[2]=mv2(t);
            for(int i=0;i<3;i++)
            {
                if(!dist.count(m[i])) //没有出现过 
                {
                    dist[m[i]]=dist[t]+1; //记录步数 
                    pre[m[i]]={'A'+i,t}; //记录转移过程 
                    q.push(m[i]); //当前点入队 
                }
            }
        }
        return -1; //走不到 
    }
    int main()
    {
        string start="12345678";
        string end;
        for(int i=1;i<=8;i++)
        {
            char x;
            cin>>x;
            end+=x;
        }
        int step=bfs(start,end);
        cout<<step<<endl;
        string res;
        while(end!=start) //还没有倒推到终点 
        {
            res+=pre[end].first; //记录操作 
            end=pre[end].second; //往前走一步 
        }
        reverse(res.begin(),res.end()); //倒序 
        if(step>0) //有操作则输出 
        {
            cout<<res;
        }
        return 0;
    }
    
    • 1

    Information

    ID
    778
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By