传送门node
给你一个矩阵和一匹马一开始的位置.而后问你在这个矩阵里边跳到每个点须要多少步.c++
由于一匹马从一个点能够跳到的位置以下图:
画的很差请见谅...git
咱们就能够开始进行bfs了,最好的板子题.spa
而后最后输出的时候由于要留5个长宽.
能够这样搞:3d
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; }