-
Notifications
You must be signed in to change notification settings - Fork 0
/
abc184_e.cpp
110 lines (87 loc) · 1.94 KB
/
abc184_e.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <bits/stdc++.h>
using namespace std;
const int maxd = 2'000;
string grid[maxd];
int moves[maxd][maxd];
int h, w;
map<char, vector<pair<int,int>>> teles;
int xs, ys, xe, ye;
void parse() {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if ('a' <= grid[i][j] and grid[i][j] <= 'z') {
teles[grid[i][j]].emplace_back(i, j);
}
if (grid[i][j] == 'S') xs = i, ys = j;
if (grid[i][j] == 'G') xe = i, ye = j;
}
}
}
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
bool valid(int x, int y) {
if (x < 0 or y < 0) return false;
if (x >= h or y >= w) return false;
if (grid[x][y] == '#') return false;
return true;
}
void bfs() {
queue<tuple<int,int,int>> q;
q.emplace(0, xs, ys);
moves[xs][ys] = 0;
set <char> vis;
while (!q.empty()) {
auto [du, xu, yu] = q.front();
if (du > moves[xu][yu]) continue;
q.pop();
for (int i = 0; i < 4; i++) {
int x2 = xu + dx[i];
int y2 = yu + dy[i];
if (!valid(x2, y2))
continue;
if (moves[x2][y2] <= moves[xu][yu] + 1)
continue;
moves[x2][y2] = moves[xu][yu] + 1;
q.emplace(moves[x2][y2], x2, y2);
}
if ('a' <= grid[xu][yu] and grid[xu][yu] <= 'z') {
if (vis.count(grid[xu][yu]))
continue;
vis.emplace(grid[xu][yu]);
for (auto [x2, y2] : teles[grid[xu][yu]]) {
if (moves[x2][y2] <= moves[xu][yu] + 1)
continue;
moves[x2][y2] = moves[xu][yu] + 1;
q.emplace(moves[x2][y2], x2, y2);
}
}
}
}
void dbg() {
for (auto [c, xs] : teles) {
cerr << c << " : ";
for (auto [x, y] : xs) cerr << "[" << x << ", " << y << "] ";
cerr << '\n';
}
}
auto run() {
cin >> h >> w;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
moves[i][j] = 1'000'000'000;
}
}
for (int i = 0; i < h;i ++) {
cin >> grid[i];
}
parse();
// dbg();
bfs();
cout << (moves[xe][ye] == 1'000'000'000 ? -1 : moves[xe][ye]) << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
run();
}
// AC, bfs