acwing-188. 武士风度的牛

考点

  • 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
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200;
const int dx[8] = {-2, -1, 1, 2, -2, -1, 1, 2},
dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
bool v[maxn][maxn];
char s[maxn][maxn];
int r, c;

struct node {
int x_, y_, step_;
node(int x = 0, int y = 0, int step = 0) : x_(x), y_(y), step_(step) {}
} bg, ed;
queue<node> q;

bool valid(int x, int y) { return x >= 1 && y >= 1 && x <= r && y <= c; }

void bfs() {
q.push(bg);
while (!q.empty()) {
node u = q.front();
q.pop();
if (u.x_ == ed.x_ && u.y_ == ed.y_) {
ed.step_ = u.step_;
return;
}
for (int i = 0; i < 8; ++i) {
int x = u.x_ + dx[i], y = u.y_ + dy[i];
if (!valid(x, y)) continue;
if (v[x][y] || s[x][y] == '*') continue;
q.emplace(x, y, u.step_ + 1);
v[x][y] = 1;
}
}
}

int main() {
cin >> c >> r;
for (int i = 1; i <= r; ++i) cin >> (s[i] + 1);
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
if (s[i][j] == 'K') {
bg.x_ = i, bg.y_ = j, bg.step_ = 0;
}
if (s[i][j] == 'H') {
ed.x_ = i, ed.y_ = j;
}
}
}
bfs();
cout << ed.step_ << endl;
return 0;
}

思路

简单的二维走地图,直接看代码即可。