a924中等

95 全國資訊學科能力競賽(2006)|靈犬尋寶

按照原題(1,3)跳躍建立邊。

解題思路

枚舉位移(±1,±3)、(±3,±1)。長方向的第一個相鄰格是馬腳位置,必須無障礙;落點也必須在0..99內且無障礙。

將可走跳躍當作單位權邊,從起點BFS。首次抵達寶物的距離最短;若無法抵達輸出impossible。蹩腳不另算一步,跳躍整體只算一步。

最多10000格、每格8邊,時間與空間皆O(100²+n)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。

Step-by-step animation

教學示意(以步驟描述中的輸入為準)

回報動畫錯誤
步驟 1 / 3

空棋盤示意

起點(0,0),終點(1,3)。

(0,0)
(1,3)
候選位移
+1,+3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin >> n;
    bool block[100][100] = {};
    while (n--) {
        int x, y;
        cin >> x >> y;
        block[x][y] = 1;
    }
    int sx, sy, tx, ty;
    cin >> sx >> sy >> tx >> ty;
    vector<vector<int>> d(100, vector<int>(100, -1));
    queue<pair<int, int>> q;
    d[sx][sy] = 0;
    q.push({sx, sy});
    while (!q.empty()) {
        auto [x, y] = q.front();
        q.pop();
        for (int dx : {-3, -1, 1, 3})
            for (int dy : {-3, -1, 1, 3})
                if (abs(dx) + abs(dy) == 4) {
                    int a = x + dx, b = y + dy,
                        fx = x + (abs(dx) == 3 ? (dx > 0 ? 1 : -1) : 0),
                        fy = y + (abs(dy) == 3 ? (dy > 0 ? 1 : -1) : 0);
                    if (a >= 0 && a < 100 && b >= 0 && b < 100 && !block[a][b] &&
                        !block[fx][fy] && d[a][b] < 0)
                        d[a][b] = d[x][y] + 1, q.push({a, b});
                }
    }
    if (d[tx][ty] < 0)
        cout << "impossible\n";
    else
        cout << d[tx][ty] << '\n';
}

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

更多