0
点赞
收藏
分享

微信扫一扫

计蒜客——一维跳棋BFS(疑问?为什么不用判断跳棋的合法性)

伢赞 2022-03-18 阅读 94

在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;

int N;
struct node {
    string s;  //当前序列
    int pos;  //当前空格位置
    vector<int> step;  //从开始到当前所有空格位置
    node() {}
    node(string ss, int p) {
        s = ss;
        pos = p;
    }
};
unordered_map<string, bool> mp;

string Strswap(string s, int a, int b) {
    char c = s[a];
    s[a] = s[b];
    s[b] = c;
    return s;
}

queue<node> q;

int main() {
    scanf("%d", &N);
    string s1, s2; //正逆向序列
    for (int i = 0; i < N; ++i) {
        s1 += '1';
        s2 += "2";
    }
    s1 += "0";
    s2 += "0";
    for (int i = 0; i < N; ++i) {
        s1 += "2";
        s2 += "1";
    }
    //printf("%s\n%s",s1.c_str(),s2.c_str());
    int dir[4] = { -2,-1,1,2 };   //每个空格有四个变化位置
    q.push(node(s1, N));
    mp[s1] = true;
    while (!q.empty()) {
        node now = q.front();
        q.pop();
        //判断是否成功
        if (now.s == s2) {
            int cnt = 0;
            for (int i = 0; i < now.step.size(); ++i) {
                if (cnt == 4) {
                    printf("%d\n", now.step[i] + 1);  //+1的目的使数组下标从1开始
                    cnt = 0;
                }
                else {
                    printf("%d ", now.step[i] + 1);
                    cnt++;
                }
            }
            break;
        }
        //空格变化
        for (int i = 0; i < 4; ++i) {          //为什么不需要判断下一步是否合理,BFS搜到最短路径到达目标即停止,所以该路径存储的空格位置即为正确答案
            int tp = now.pos + dir[i];
            if (tp >= 0 && tp < 2 * N + 1) {
                string ts = Strswap(now.s, now.pos, tp);
                if (!mp[ts]) {
                    mp[ts] = true;
                    node tn = node(ts, tp);
                    tn.step = now.step;
                    tn.step.push_back(tp);
                    q.push(tn);
                    cout << tp << endl;
                }
            }
        }
    }
    while (1);
    return 0;
}

 

举报

相关推荐

0 条评论