给你一个矩阵和一匹马一开始的位置.然后问你在这个矩阵里边跳到每一个点需要多少步.
因为一匹马从一个点可以跳到的位置如下图:
画的不好请见谅...
我们就可以开始进行bfs了,最好的板子题.
然后最后输出的时候因为要留5个长宽.
可以这样搞:
cout << setw(5) << std::left << maze[i][j];
#include <bits/stdc++.h>
#include <queue>
#define N 100010
#define M 1010
#define _ 0
using namespace std;
struct node {
int x, y, bushu;
};
int m, n, x, y;
int u[8]= {1, 2, 2, 1, -1, -2, -2, -1};
int v[8]= {-2, -1, 1, 2, 2, 1, -1, -2};
int maze[401][401];
queue<node> q;
int read() {
int s = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
return f ? -s : s;
}
void bfs(int r, int t) {
memset(maze, -1, sizeof(maze));
maze[r][t] = 0;
q.push((node) {r, t, 0});
while (!q.empty()) {
node a = q.front();
q.pop();
for (int i = 0; i <= 7; i++) {
int fx = a.x + u[i];
int fy = a.y + v[i];
if (fx >= 1 && fx <= n && fy >= 1 && fy <= m && maze[fx][fy] == -1) {
maze[fx][fy] = a.bushu + 1;
q.push((node) {fx, fy, a.bushu + 1});
}
}
}
}
int main() {
n = read(), m = read(), x = read(), y = read();
bfs(x, y);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
cout << setw(5) << std::left << maze[i][j];
puts("");
}
return 0^_^0;
}
原文:https://www.cnblogs.com/zzz-hhh/p/11703349.html