-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortestPathAllKeys.cpp
More file actions
52 lines (48 loc) · 1.88 KB
/
shortestPathAllKeys.cpp
File metadata and controls
52 lines (48 loc) · 1.88 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
52
class Solution {
public:
const static inline vector<int> dirs = {-1, 0, 1, 0, -1};
int shortestPathAllKeys(vector<string>& grid) {
int m = grid.size(), n = grid[0].size();
int k = 0, si = 0, sj = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
char c = grid[i][j];
if (islower(c)) ++k;
else if (c == '@') {
si = i;
sj = j;
}
}
}
queue<tuple<int, int, int>> q{{{si, sj, 0}}};
vector<vector<vector<bool>>> vis(m, vector<vector<bool>>(n, vector<bool>(1 << k)));
vis[si][sj][0] = true;
int ans = 0;
while (!q.empty()) {
for (int t = q.size(); t; --t) {
auto [i, j, state] = q.front();
q.pop();
if (state == (1 << k) - 1) return ans;
for (int h = 0; h < 4; ++h) {
int x = i + dirs[h], y = j + dirs[h + 1];
if (x >= 0 && x < m && y >= 0 && y < n) {
char c = grid[x][y];
if (c == '#' || (isupper(c) && (state >> (c - 'A') & 1) == 0)) continue;
int nxt = state;
if (islower(c)) nxt |= 1 << (c - 'a');
if (!vis[x][y][nxt]) {
vis[x][y][nxt] = true;
q.push({x, y, nxt});
}
}
}
}
++ans;
}
return -1;
}
};
// 作者:ylb
// 链接:https://leetcode.cn/problems/shortest-path-to-get-all-keys/solutions/1960449/by-lcbin-mk6o/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。