马的遍历
题目描述
有一个 n × m n \times m n×m 的棋盘,在某个点 ( x , y ) (x, y) (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n , m , x , y n, m, x, y n,m,x,y。
输出格式
一个 n × m n \times m n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 − 1 -1 −1)。
样例 #1
样例输入 #1
3 3 1 1
样例输出 #1
0 3 2
3 -1 1
2 1 4
提示
数据规模与约定
对于全部的测试点,保证 1 ≤ x ≤ n ≤ 400 1 \leq x \leq n \leq 400 1≤x≤n≤400, 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1≤y≤m≤400。
解题思路
这个问题可以使用广度优先搜索 (BFS) 来解决。我们首先初始化一个大小为 n x m 的矩阵来存储到达每个位置所需要的最少步数。然后,从马的起始位置开始,将它能够到达的每一个位置添加到一个队列中,并不断更新这些位置在矩阵中的值,直到队列为空。
C++ 解题代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<istream>
#include<iomanip>
#include<ostream>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<fstream>
#include<stack>
#include<ctime>
#include<deque>
#include<queue>
#include <sstream>
#include <numeric>
#pragma warning (disable:4996)
using namespace std;
const int dx[8] = { 1, 1, 2, 2, -1, -1, -2, -2 };
const int dy[8] = { 2, -2, 1, -1, 2, -2, 1, -1 };
int main() {
int n, m, x, y;
cin >> n >> m >> x >> y;
vector<vector<int>> board(n, vector<int>(m, -1));//初始化一个n*m的矩阵,值为-1
board[x - 1][y - 1] = 0;//起点为0
queue<pair<int, int>> q;
q.push({ x - 1, y - 1 });//起点入队
while (!q.empty()) {
int x = q.front().first, y = q.front().second;
q.pop();
for (int i = 0; i < 8; ++i) {//八个方向
int nx = x + dx[i], ny = y + dy[i];
if (0 <= nx && nx < n && 0 <= ny && ny < m && board[nx][ny] == -1) {//判断是否越界,是否访问过
board[nx][ny] = board[x][y] + 1;//标记加1
q.push({ nx, ny });//入队
}
}
}
//输出
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
return 0;
}
代码解析
首先,定义了两个数组 dx
和 dy
,它们表示了马可以移动的 8 个方向。然后在 main()
函数中,从输入中读取棋盘的大小 n
和 m
,以及马的起始位置 x
和 y
。然后初始化一个大小为 n * m
的二维矩阵 board
,并将所有元素初始化为 -1
。
然后,将马的起始位置添加到队列 q
中,并将该位置在 board
中的值设置为 0
。这表示马从起始位置开始移动。
接下来,进行一个 while 循环,当队列 q
不为空时,取出队列的一个元素,并计算马可以到达的新位置。如果新位置在棋盘内,且 board
中的值为 -1
(表示马还未到达这个位置),则将这个位置添加到队列 q
中,并更新 board
中对应的值。
最后,遍历 board
,打印出马到达每个位置的最少步数。
总结
基础的图遍历问题,通过广度优先搜索 (BFS) 可以找到最优解。类似的问题可以考虑使用 BFS 或者深度优先搜索 (DFS) 来解决。