【计蒜客】三阶平面魔方

题目

在这里插入图片描述

思路

用bfs,分别模拟每一步的转动情况

代码

#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<string,bool> ma;//标记
struct node{
    string statu;
    int step;
}first,last;
queue<node> q;

string next_dir(int i,string s){
    char temp;
    if(i==1){//第一行左转
        temp=s[0];
        s[0]=s[1];
        s[1]=s[2];
        s[2]=temp;
    }else if(i==2){//第二行左转
        temp=s[3];
        s[3]=s[4];
        s[4]=s[5];
        s[5]=temp;
    }else if(i==3){//第三行左转
        temp=s[6];
        s[6]=s[7];
        s[7]=s[8];
        s[8]=temp;
    }else if(i==4){//第一行往右
        temp=s[2];
        s[2]=s[1];
        s[1]=s[0];
        s[0]=temp;
    }else if(i==5){//第二行往右
        temp=s[5];
        s[5]=s[4];
        s[4]=s[3];
        s[3]=temp;
    }else if(i==6){//第三行往右
        temp=s[8];
        s[8]=s[7];
        s[7]=s[6];
        s[6]=temp;
    }else if(i==7){//第一列往上
        temp=s[0];
        s[0]=s[3];
        s[3]=s[6];
        s[6]=temp;
    }else if(i==8){//第二列往上
        temp=s[1];
        s[1]=s[4];
        s[4]=s[7];
        s[7]=temp;
    }else if(i==9){//第三列往上
        temp=s[2];
        s[2]=s[5];
        s[5]=s[8];
        s[8]=temp;
    }else if(i==10){//第一列往下
        temp=s[6];
        s[6]=s[3];
        s[3]=s[0];
        s[0]=temp;
    }else if(i==11){//第二列往下
        temp=s[7];
        s[7]=s[4];
        s[4]=s[1];
        s[1]=temp;
    }else{         //第三列往下
        temp=s[8];
        s[8]=s[5];
        s[5]=s[2];
        s[2]=temp;
    }
    return s;
}
int main(){
    string t1,t2,t3;
    cin>>t1>>t2>>t3;
    first.statu=t1+t2+t3;
    last.statu="123456789";
    ma[first.statu]=true;
    q.push(first);
    node a,next;
    while(!q.empty()){
        a=q.front();
        q.pop();
        if(a.statu==last.statu){//出口
            cout<<a.step<<endl;
            break;
        }
        for(int i=1;i<=12;i++){
            string tem=next_dir(i,a.statu);
            if(!ma[tem]){
                ma[tem]=true;
                next.statu=tem;
                next.step=a.step+1;
                q.push(next);
            }
        }
    }
    if(a.statu!=last.statu){
        cout<<"-1"<<endl;
    }
    return 0 ;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值