P1443. 马的遍历

考点

  • BFS

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>

using namespace std;

struct Node
{
int x_, y_;
Node(int x = 0, int y = 0) : x_(x), y_(y) {}
};

queue<Node> q;

int N, M, ans[450][450], walk[8][2] = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}, {1, -2}, {2, -1}};

void bfs()
{
while (!q.empty())
{
Node u = q.front();
q.pop();
int ux = u.x_, uy = u.y_;
for (int i = 0; i < 8; ++i)
{
int x = ux + walk[i][0], y = uy + walk[i][1];
if (x < 1 || x > N || y < 1 || y > M || ans[x][y] != -1)
continue;
ans[x][y] = ans[ux][uy] + 1;
q.emplace(x, y);
}
}
}

int main()
{
int x, y;
cin >> N >> M >> x >> y;
memset(ans, -1, sizeof(ans));
q.emplace(x, y);
ans[x][y] = 0;
bfs();
for (int i = 1; i <= N; ++i, puts(""))
for (int j = 1; j <= M; ++j)
printf("%-5d", ans[i][j]);
return 0;
}

思路

BFS的模板题,有三个注意点:

  • 答案数组初始值不能为0,因为起点本身的答案就是0
  • BFS要设置标志数组不走回头路!在这里答案数组也可以作为标志数组使用,因为访问过的点其答案肯定不为初始值
  • 输出的格式是左对齐并占5个字宽