问题 1426: [蓝桥杯][历届试题]九宫重排

点击打开题目

#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<algorithm>
#include<iostream>

using namespace std;


string a,b;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};   //上右下左。
set<int>s;                                     //用集合来统计某个状态是否出现
typedef struct Node {
    string s;    //当前状态
    int pos;     //.在s中的位置
    int step;    //起始状态到当前状态的步数
}node;
//判断是否越界。
bool judge(int x,int y) {
    if(x>=0&&x<3&&y>=0&&y<3) return true;
    return false;
}
//字符串转数字。
int cal(string str) {
    int num = 0;
    for(int i = 0; i < str.length(); i++) {
        num = num*10 + str[i]-'0';
    }
    return num;
}
int solve(string str1,string str2,int pos) {
    queue<node>qu;
    node cur,nex;
    cur.s = str1;
    cur.pos = pos;
    cur.step = 0;
    int index1,index2;
    s.insert(cal(cur.s));
    qu.push(cur);
    int x,y,dx,dy;
    while(!qu.empty()) {
        cur = qu.front();
        qu.pop();
        x = cur.pos/3;
        y = cur.pos%3;
        index1 = cur.pos;
        for(int i = 0; i < 4; i++) {
            dx = x + dir[i][0];
            dy = y + dir[i][1];
            index2 = dx*3 + dy;
            if(judge(dx,dy)) {
               swap(cur.s[index1],cur.s[index2]);
               if(s.count(cal(cur.s)) == 0) {
                    nex.s = cur.s;
                    nex.pos = index2;
                    nex.step = cur.step + 1;
                    if(nex.s == str2) return nex.step;
                    s.insert(cal(nex.s));
                    qu.push(nex);
               }
               swap(cur.s[index1],cur.s[index2]);
            }
        }
    }
    return -1;
}

int main() {
    while(cin>>a>>b) {
        if(a == b) {
            puts("0");
        }
        else {
            s.clear();
            for(int i = 0; i < b.length(); i++) {
                if(b[i]=='.') {  //把点转化为0
                    b[i] = '0';
                    break;
                }
            }
            int ans;
            for(int i = 0; i < a.length(); i++) {
                if(a[i]=='.') {
                    a[i] = '0';
                    ans = solve(a,b,i);
                    break;
                }
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}

    原文作者:九宫格问题
    原文地址: https://blog.csdn.net/wyxeainn/article/details/79741971
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞