a758簡單棋盤八方向的 BFS 最短步數

CPE:Knight Moves (UVa 439)

把棋格作為節點,以等權邊搜尋最少騎士步。

前往題目練習 →回報教學錯誤每題時間與空間 O(64),棋盤大小固定。

解題思路

棋格映射為 (x,y),其中 a–h 對應 0–7、1–8 對應 0–7。騎士恰有八種位移 (±1,±2)、(±2,±1),只有新座標仍在 0–7 內才建立可走的邊。

每步成本都是 1,BFS 的佇列依距離層次擴展,第一次抵達某格的距離就是最短。起點距離為 0,入隊時便標記以避免重複;起終點相同自然輸出 0。位置配對讀到 EOF,輸出指定完整句子,1 步仍使用 moves。

Step-by-step animation

示意:a1 到 d4

回報動畫錯誤
步驟 1 / 3

起點

a1=(0,0),距離 0。

a1:0
b3:?
d4:?
distance
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <queue>
#include <array>
using namespace std;
int main() {
    string a, b;
    int dx[] = {1, 1, -1, -1, 2, 2, -2, -2}, dy[] = {2, -2, 2, -2, 1, -1, 1, -1};
    while (cin >> a >> b) {
        int d[8][8];
        for (auto &row : d)
            for (int &v : row)
                v = -1;
        queue<pair<int, int>> q;
        int sx = a[0] - 'a', sy = a[1] - '1';
        d[sx][sy] = 0;
        q.push({sx, sy});
        while (!q.empty()) {
            auto [x, y] = q.front();
            q.pop();
            for (int k = 0; k < 8; ++k) {
                int u = x + dx[k], v = y + dy[k];
                if (u >= 0 && u < 8 && v >= 0 && v < 8 && d[u][v] < 0) {
                    d[u][v] = d[x][y] + 1;
                    q.push({u, v});
                }
            }
        }
        cout << "To get from " << a << " to " << b << " takes " << d[b[0] - 'a'][b[1] - '1']
             << " knight moves.\n";
    }
}

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

更多