蓝桥杯 历届试题 九宫重排

问题描述
  如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。

我们把第一个图的局面记为:12345678.
把第二个图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。
输入格式
  输入第一行包含九宫的初态,第二行包含九宫的终态。
输出格式
  输出最少的步数,如果不存在方案,则输出-1。
样例输入
12345678.
123.46758
样例输出
3
样例输入
13524678.
46758123.
样例输出
22

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<set> 
#define N 20005
using namespace std;

char mp[3][3], gp[3][3];
int dir[4][2] = {0,1, 1,0, -1,0, 0,-1};
char str[10];
struct node{
    int x, y;
    int step;
    char cur_mp[3][3];//记录当前图案
    node(){
    }
    node(int x, int y, int step){
        this->x = x;
        this->y = y;
        this->step = step;
    }
};
set<int>st;
queue<node>q;
bool check(node cur){
    for(int i=0; i<3; ++i)
        for(int j=0; j<3; ++j)
            if(cur.cur_mp[i][j] != gp[i][j])
                return false;
    return true;
}

int cal(node cur){//每一次移动将会映射到一个不同的整数
    int ss = 0;
    for(int i=0; i<3; ++i)
        for(int j=0; j<3; ++j)
            if(cur.cur_mp[i][j] != '.')
                ss = ss*10+(cur.cur_mp[i][j]-'0');
            else ss = ss*10+9;
    return ss;
}

void bfs(){
    st.clear();
    if(!q.empty())
        st.insert(cal(q.front()));
    while(!q.empty()){
        node cur = q.front();
        q.pop();
        if(check(cur)) {
            cout<<cur.step<<endl;
            return ;
        }
        
        for(int i=0; i<4; ++i){
            int xx = cur.x+dir[i][1];
            int yy = cur.y+dir[i][0];
            if(xx<0 || xx>2 || yy<0 || yy>2) continue;
            node nt = node(xx, yy, cur.step+1);
            memcpy(nt.cur_mp, cur.cur_mp, sizeof(cur.cur_mp));
            nt.cur_mp[cur.x][cur.y]^=nt.cur_mp[xx][yy];
            nt.cur_mp[xx][yy]^=nt.cur_mp[cur.x][cur.y];
            nt.cur_mp[cur.x][cur.y]^=nt.cur_mp[xx][yy];
            int val = cal(nt);
            if(st.find(val) != st.end()) continue;
            st.insert(val);
            q.push(nt);
        }
    }
    cout<<-1<<endl;
}

int main() {
    while(cin>>str){
        int bx, by;
        while(!q.empty()) q.pop();
        int len = 0;
        for(int i=0; i<3; ++i)
            for(int j=0; j<3; ++j){
                mp[i][j] = str[len++];
                if(mp[i][j] == '.') bx=i, by=j;
            }
        node cur = node(bx, by, 0);
        memcpy(cur.cur_mp, mp, sizeof(mp));
        q.push(cur);
        cin>>str;
        len = 0;
        for(int i=0; i<3; ++i)
            for(int j=0; j<3; ++j)
                gp[i][j] = str[len++];
        bfs();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值