BFS アルゴリズム ホース トラバーサル

トピックの説明

n*m のチェス盤 (1<n, m<=400) があり、ある地点に馬がいて、馬が盤上の任意の地点に到達するための最小歩数を計算する必要があります。

答え:

この質問の主な難点は、馬の動きです。

馬が動く範囲を描いていれば、アイデアは非常に明確になります

上の図からわかるように、馬の検索範囲は開始点 (0,0) から 8 つあり、変換コードは次のようになります。

int dx[] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};

順番に最後まで検索し、最小パスを取得できます

コード

#include <bits/stdc++.h>
using namespace std;
int v[400][400];
struct node {int x, y, s;};
queue<node> q;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};
int main() {
    int n, m, sX, sY;
    cin >> n >> m >> sX >> sY;
    memset(v, -1, sizeof(v));
    q.push((node){sX, sY, 0});
    v[sX][sY] = 0;
    while (!q.empty()) {
        node current = q.front();
        for (int i = 0; i < 8; i++) {
            int tx = current.x + dx[i];
            int ty = current.y + dy[i];
            if (tx <= n && tx >= 1 && ty <= m && ty >= 1 && v[tx][ty] == -1) {
                q.push((node){tx, ty, current.s + 1});
                v[tx][ty] = current.s + 1;
            }
        }
        q.pop();
    }
    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= m; j++)
            printf("%-5d", v[i][j]);
        printf("\n");
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_45462923/article/details/114647905