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;
}

猜你喜欢

转载自blog.csdn.net/qq_45462923/article/details/114647905