P2960. Invasion of the Milkweed G

考点

  • 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
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200;
const int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
const int dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};
char s[maxn][maxn];
bool v[maxn][maxn];
int r, c, tot;

struct node {
int x_, y_, step_;
node(int x = 0, int y = 0, int step = 0) : x_(x), y_(y), step_(step) {}
} bg;
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();
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;
--tot;
if (!tot) {
cout << u.step_ + 1 << endl;
return;
}
q.emplace(x, y, u.step_ + 1);
v[x][y] = 1;
}
}
}

int main() {
cin >> c >> r >> bg.y_ >> bg.x_;
bg.x_ = r + 1 - bg.x_;
for (int i = 1; i <= r; ++i) cin >> (s[i] + 1);
tot = r * c;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
if (s[i][j] == '*') --tot;
}
}
bfs();
return 0;
}

思路

正常的走地图,直接看代码即可。

唯一的坑点就是输入..........所有的横纵坐标都倒过来了,所以有这行代码:

1
cin >> c >> r >> bg.y_ >> bg.x_;

关键是这句话:

(1,1)是左下角的格(也就是说坐标排布跟一般的X,Y坐标相同)

代码改成这样:

1
bg.x_ = r + 1 - bg.x_;