-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathgrid-teleportation-traversal.cpp
More file actions
51 lines (50 loc) · 1.73 KB
/
grid-teleportation-traversal.cpp
File metadata and controls
51 lines (50 loc) · 1.73 KB
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
// Time: O(m * n)
// Space: O(m * n)
// 0-1 bfs
class Solution {
public:
int minMoves(vector<string>& matrix) {
static const vector<pair<int, int>> DIRECTIONS = {{0, 1}, {0, -1},
{1, 0}, {-1, 0}};
const int m = size(matrix), n = size(matrix[0]);
vector<vector<pair<int, int>>> lookup(26);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '.' || matrix[i][j] == '#') {
continue;
}
lookup[matrix[i][j] - 'A'].emplace_back(i, j);
}
}
vector<vector<bool>> lookup2(m, vector<bool>(n));
deque<tuple<int, int, int>> dq = {{0, 0, 0}};
while (!empty(dq)) {
const auto [step, i, j] = dq.front(); dq.pop_front();
if (lookup2[i][j]) {
continue;
}
lookup2[i][j] = true;
if (i == m - 1 && j == n - 1) {
return step;
}
for (const auto& [di, dj] : DIRECTIONS) {
const int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < m && 0 <= nj && nj < n && matrix[ni][nj] != '#' && !lookup2[ni][nj])) {
continue;
}
dq.emplace_back(step + 1, ni, nj);
}
if (matrix[i][j] == '.') {
continue;
}
for (const auto& [ni, nj] : lookup[matrix[i][j] - 'A']) {
if (lookup2[ni][nj]) {
continue;
}
dq.emplace_front(step, ni, nj);
}
lookup[matrix[i][j] - 'A'].clear();
}
return -1;
}
};