侧边栏壁纸
博主头像
GabrielxD

列車は必ず次の駅へ。では舞台は?私たちは?

  • 累计撰写 675 篇文章
  • 累计创建 128 个标签
  • 累计收到 22 条评论

目 录CONTENT

文章目录

【BFS】八数码 - 交换记录

GabrielxD
2022-12-29 / 0 评论 / 0 点赞 / 158 阅读 / 751 字
温馨提示:
本文最后更新于 2022-12-29,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目

179. 八数码


在一个 3×33×3 的网格中, 181 \sim 888 个数字和一个 X 恰好不重不漏地分布在这 3×33×3 的网格中。

例如:

1 2 3
X 4 6
7 5 8

在游戏过程中,可以把 X 与其上、下、左、右四个方向之一的数字交换(如果存在)。

我们的目的是通过交换,使得网格变为如下排列(称为正确排列):

1 2 3
4 5 6
7 8 X

例如,示例中图形就可以通过让 X 先后与右、下、右三个方向的数字交换成功得到正确排列。

交换过程如下:

1 2 3   1 2 3   1 2 3   1 2 3
X 4 6   4 X 6   4 5 6   4 5 6
7 5 8   7 5 8   7 X 8   7 8 X

X 与上下左右方向数字交换的行动记录为 udlr

现在,给你一个初始网格,请你通过最少的移动次数,得到正确排列。

输入格式

输入占一行,将 3×33×3 的初始网格描绘出来。

例如,如果初始网格如下所示:

1 2 3 
x 4 6 
7 5 8

则输入为:1 2 3 x 4 6 7 5 8

输出格式

输出占一行,包含一个字符串,表示得到正确排列的完整行动记录。

如果答案不唯一,输出任意一种合法方案即可。

如果不存在解决方案,则输出 unsolvable

输入样例:

2  3  4  1  5  x  7  6  8

输出样例

ullddrurdllurdruldr

解题

方法一:BFS

思路

求「最少能从初始状态到达结束状态的步数」问题的 BFS 模板

同类题目:【BFS】八数码 - 最少交换次数

代码

#include <iostream>
#include <unordered_map>
#include <queue>
#include <vector>

using namespace std;

const int DIRS[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const char DIR_NAMES[4] = {'u', 'd', 'l', 'r'};
string ori, tgt = "12345678x";
unordered_map<string, int> poses;
unordered_map<string, string> prevs;
unordered_map<string, char> prev_dirs;
queue<string> que;

int main() {
    int ori_pos = 0;
    for (int i = 0; i < 9; ++i) {
        char c;
        scanf("%c ", &c);
        if (c == 'x') ori_pos = i;
        ori += c;
    }
    poses[ori] = ori_pos;
    que.push(ori);
    while (!que.empty()) {
        string curr = que.front();
        que.pop();
        if (curr == tgt) {
            vector<char> path;
            for (; prevs.find(curr) != prevs.end(); curr = prevs[curr]) path.push_back(prev_dirs[curr]);
            for (int i = path.size() - 1; i >= 0; --i) putchar(path[i]);
            puts("");
            
            return 0;
        }
        int pos = poses[curr];
        int x = pos / 3, y = pos % 3;
        for (int i = 0; i < 4; ++i) {
            int nx = x + DIRS[i][0], ny = y + DIRS[i][1];
            if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
                int npos = nx * 3 + ny;
                string ns(curr);
                swap(ns[pos], ns[npos]);
                if (poses.find(ns) == poses.end()) {
                    poses[ns] = npos;
                    prevs[ns] = curr;
                    prev_dirs[ns] = DIR_NAMES[i];
                    que.push(ns);
                }
            }
        }
    }
    puts("unsolvable");
    
    return 0;
}
0

评论区