【问题】计算出马到达棋盘任意一点最少要走多少步?
【输入】棋盘大小n*m,马的坐标(x, y)
3 3 1 1
【输出】
0 3 2
3 -1 1
2 1 4
【解析】
- 使用广度优先搜索。
- 注意:马走“日”,走的方向有八个
#include<bits/stdc++.h>
using namespace std;
queue<pair<int, int>> q;
int step[500][500];
bool visited[500][500];
const int x_gain[] = {-1, -2, -2, -1, 1, 2, 2, 1};
const int y_gain[] = {2, 1, -1, -2, -2, -1, 1, 2};
int main()
{
memset(step, -1, sizeof(step));
memset(visited, false, sizeof(visited));
int n, m, x, y;
cin >> n >> m >> x >> y;
q.push(make_pair(x, y));//生成pair
step[x][y] = 0;
visited[x][y] = true;
while(!q.empty())
{
int x_now = q.front().first;
int y_now = q.front().second;
q.pop();
for (int i = 0; i < 8; i++)