Approach
Breadth-first search
For Shortest Path to Get All Keys, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 64 lines of C++ from the credited upstream file 864.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct T {2 int i;3 int j;4 int keys; 5};6 7class Solution {8 public:9 int shortestPathAllKeys(vector<string>& grid) {10 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};11 const int m = grid.size();12 const int n = grid[0].length();13 const int keysCount = getKeysCount(grid);14 const int kKeys = (1 << keysCount) - 1;15 const vector<int> start = getStart(grid);16 queue<T> q{{{start[0], start[1], 0}}};17 vector<vector<vector<bool>>> seen(18 m, vector<vector<bool>>(n, vector<bool>(kKeys)));19 seen[start[0]][start[1]][0] = true;20 21 for (int step = 1; !q.empty(); ++step)22 for (int sz = q.size(); sz > 0; --sz) {23 const auto [i, j, keys] = q.front();24 q.pop();25 for (const auto& [dx, dy] : kDirs) {26 const int x = i + dx;27 const int y = j + dy;28 if (x < 0 || x == m || y < 0 || y == n)29 continue;30 const char c = grid[x][y];31 if (c == '#')32 continue;33 const int newKeys = 'a' <= c && c <= 'f' ? keys | 1 << c - 'a' : keys;34 if (newKeys == kKeys)35 return step;36 if (seen[x][y][newKeys])37 continue;38 if ('A' <= c && c <= 'F' && (newKeys >> c - 'A' & 1) == 0)39 continue;40 q.emplace(x, y, newKeys);41 seen[x][y][newKeys] = true;42 }43 }44 45 return -1;46 }47 48 private:49 int getKeysCount(const vector<string>& grid) {50 int count = 0;51 for (const string& s : grid)52 count += ranges::count_if(s, [](char c) { return 'a' <= c && c <= 'f'; });53 return count;54 }55 56 vector<int> getStart(const vector<string>& grid) {57 for (int i = 0; i < grid.size(); ++i)58 for (int j = 0; j < grid[0].length(); ++j)59 if (grid[i][j] == '@')60 return {i, j};61 throw;62 }63};64