b605困難

CSES 1670|交換遊戲(Swap Game)

以全部九個數字的排列為狀態,從起點和目標同時搜尋最少交換。

解題思路

一個狀態是列優先的九字元排列,共至多 9!=362880 種。方格有 12 組水平或垂直相鄰位置,每一組交換形成一條無向、成本 1 的狀態邊。目標是 123456789,因此 BFS 的層數就是最少交換次數。

為減少展開,從輸入與目標各維護一個完整 BFS 前緣,每回合擴展較小的一側。每次只擴展整個同深度層,遇到另一側已訪問狀態時,兩邊距離相加就是最短路;此前兩個已搜尋的距離球沒有交集,所以不存在更短的未發現路徑。普通滑塊遊戲只許與空格交換,本題沒有空格且任意相鄰數字都能交換。

最壞 O(12·9!) 時間、O(9!·9) 狀態字串空間,另有 Python 字典與集合負擔。固定 3×3,雙向 BFS 常減少實際狀態,但 Python 一秒仍需量測。

Step-by-step animation

獨立教學例子(不一定是公開範例)

回報動畫錯誤
步驟 1 / 3

步驟 1:起始排列 213456789

起始排列 213456789,與目標只差首兩格

213
456
789
已走
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string start;
    for (int i = 0, x; i < 9; i++) {
        cin >> x;
        start += char('0' + x);
    }
    string goal = "123456789";
    if (start == goal) {
        cout << 0 << '\n';
        return 0;
    }
    vector<pair<int, int>> edges;
    for (int i = 0; i < 9; i++) {
        if (i % 3 < 2)
            edges.push_back({i, i + 1});
        if (i < 6)
            edges.push_back({i, i + 3});
    }
    unordered_set<string> a{start}, b{goal};
    unordered_map<string, int> da{{start, 0}}, db{{goal, 0}};
    while (!a.empty()) {
        if (a.size() > b.size()) {
            swap(a, b);
            swap(da, db);
        }
        unordered_set<string> next;
        for (auto s : a) {
            int d = da[s] + 1;
            for (auto [i, j] : edges) {
                swap(s[i], s[j]);
                if (!da.count(s)) {
                    if (db.count(s)) {
                        cout << d + db[s] << '\n';
                        return 0;
                    }
                    da[s] = d;
                    next.insert(s);
                }
                swap(s[i], s[j]);
            }
        }
        a.swap(next);
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多