-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathABC_184_E.cpp
98 lines (78 loc) · 2 KB
/
ABC_184_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
#include <iostream>
#include <queue>
#include <utility>
#include <string>
#include <cstring>
using namespace std;
string maps[2000];
int visited[2000][2000];
bool teleported[26];
vector<pair<int, int> > teleport[26];
pair<int, int> start, goal;
int dir[][2] = { -1, 0, 0, -1, 0, 1,1,0 };
int main() {
int h, w;
cin >> h >> w;
for (int i = 0; i < h; i++)
{
cin >> maps[i];
for (int j = 0; j < maps[i].size(); j++)
{
if (maps[i][j] >= 'a' && maps[i][j] <= 'z')
{
teleport[maps[i][j] - 'a'].push_back(make_pair(i, j));
}
else if (maps[i][j] == 'S')
{
start = make_pair(i, j);
}
else if (maps[i][j] == 'G')
{
goal = make_pair(i, j);
}
}
}
memset(visited, -1, sizeof(visited));
int result = -1;
queue< pair<int, int> > que;
que.push(start);
visited[start.first][start.second] = 0;
while (!que.empty())
{
pair<int, int> next = que.front();
que.pop();
if (next.first == goal.first && next.second == goal.second)
{
result = visited[next.first][next.second];
break;
}
for (int d = 0; d < 4; d++)
{
int x = next.first + dir[d][0];
int y = next.second + dir[d][1];
if (x >= h || x < 0 || y >= w || y < 0 || visited[x][y] != -1 || maps[x][y] == '#')
{
continue;
}
visited[x][y] = visited[next.first][next.second] + 1;
que.push(make_pair(x, y));
}
// teleport
if (maps[next.first][next.second] >= 'a' && maps[next.first][next.second] <= 'z' && teleported[maps[next.first][next.second] - 'a'] == false)
{
teleported[maps[next.first][next.second] - 'a'] = true;
for (int i = 0; i < teleport[maps[next.first][next.second] - 'a'].size(); i++)
{
int x = teleport[maps[next.first][next.second] - 'a'][i].first;
int y = teleport[maps[next.first][next.second] - 'a'][i].second;
if (x >= h || x < 0 || y >= w || y < 0 || visited[x][y] != -1 || maps[x][y] == '#')
{
continue;
}
visited[x][y] = visited[next.first][next.second] + 1;
que.push(make_pair(x, y));
}
}
}
cout << result << endl;
}