跳到正文

题解

题解:P1443 马的遍历

Judgement_Bird约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月31日
更新
2025年12月31日
篇幅
约 4 分钟
题目
P1443

版本

  1. v1当前

思路

这道题是一个典型的BFS题目

代码实现

因为马走日,每次有 88 个可能的方向

因此定义两个一维数组dx,dydx,dy

C++
int dx[] = {0, -2, -1, 1, 2, 2, 1, -1, -2};
int dy[] = {0, 1, 2, 2, 1, -1, -2, -2, -1};
//i为向第i个方向走的距离

另外使用ququ存储走到的每一个点,ss存储走到的每一个点的步数(因为起点不需要动,所以为00,又因为无法走到的输出−1-1,所以全部初始化为−1-1)

C++
struct Node{
    int x, y;
};
queue<Node> qu;
memset(s, -1, sizeof(s));
int s[410][410];
s[x][y] = 0;
qu.push({x, y});
//x,y为题中所给数据

将队列中的每一个点进行遍历,每次从队列取出一个位置 (x,y)(x,y),尝试 8 个方向,如果新位置 在棋盘内&未被访问过s[nx][ny] == -1,则步数=s[x][y]+1步数 = s[x][y] + 1,并加入队列。

C++
while (!qu.empty()){
    Node now = qu.front();
    for(int i = 1; i <= 8; i++){
        nx = now.x + dx[i];
        ny = now.y + dy[i];
        if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && s[nx][ny] == -1){
            qu.push({nx, ny});
            s[nx][ny] = s[now.x][now.y] + 1;
        }
    }
}

最后输出每一个点对应的步数

C++
for (int i = 1; i <= n; i++){
    for (int j = 1; j <= m; j++){
        cout<< s[i][j] << " ";
    }
    cout<<'\n';
}

代码

C++
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y;
int s[410][410];
int dx[9] = {0, -2, -1, 1, 2, 2, 1, -1, -2};
int dy[9] = {0, 1, 2, 2, 1, -1, -2, -2, -1};
struct Node
{
    int a, b;
};
queue<Node> qu;
int main()
{
    cin >> n >> m >> x >> y;
    memset(s, -1, sizeof(s));
    s[x][y] = 0;
    qu.push({x, y});
    while (!qu.empty())
    {
        Node now = qu.front();
        int tx, ty;
        qu.pop();
        for (int i = 1; i <= 8; i++)
        {
            tx = now.a + dx[i];
            ty = now.b + dy[i];

            if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && s[tx][ty] == -1)
            {
                qu.push({tx, ty});
                s[tx][ty] = s[now.a][now.b] + 1;
            }
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cout << s[i][j] << " ";
        }
        cout << '\n';
    }
    return 0;
}
原文