439 - Knight Moves

Problem.png

騎士的移動
經(jīng)典的BFS,但是統(tǒng)計從起點到終點需要多少步的話要思考一下,每次擴(kuò)展到新方塊的時候,新方塊到起點的步數(shù)是在當(dāng)前出隊的方塊到起點的距離+1,這是一個類似于迭代的過程??體會一下吧。。

#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <cstring>
using namespace std;

struct point {
    int x;
    int y;
    
    point(int x, int y) : x(x), y(y) {}
};

// 用step數(shù)組記錄棋盤上每個方塊從起點開始走出的步數(shù)
int step[8][8];

// 騎士有八個方向可以走
int dr[8] = {-2, -1, 1, 2, -2, -1, 1, 2};
int dc[8] = {-1, -2, -2, -1, 1, 2, 2, 1};

int bfs(point s, point d) {
    queue<point> q;
    q.push(s);
    step[s.x][s.y] = 0;
    while (!q.empty()) {
        point u = q.front();
        q.pop();
        if (u.x == d.x && u.y == d.y) break;
        for (int i = 0; i < 8; i++) {
            int dx = u.x + dr[i];
            int dy = u.y + dc[i];
            if (dx >= 0 && dx <= 7 && dy >= 0 && dy <= 7 && step[dx][dy] < 0) {
                q.push(point(dx, dy));
                // 對于當(dāng)前方塊可以移動到的方塊,從起點走出的步數(shù)要在當(dāng)前方塊的基礎(chǔ)上+1
                step[dx][dy] = step[u.x][u.y] + 1;
            }
        }
    }
    return step[d.x][d.y];
}

int main() {
    string start, dest;
    while (cin >> start >> dest) {
        memset(step, -1, sizeof(step));
        int x1 = start[1] - '0' - 1;
        int y1 = start[0] - 'a';
        int x2 = dest[1] - '0' - 1;
        int y2 = dest[0] - 'a';
        
        point s(x1, y1);
        point d(x2, y2);
        int ans = bfs(s, d);
        printf("To get from %s to %s takes %d knight moves.\n", start.c_str(), dest.c_str(), ans);
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容