- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 68 lines of C++ from the credited upstream file 3552.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 4 int minMoves(vector<string>& matrix) {5 if (matrix.back().back() == '#')6 return -1;7 8 vector<vector<pair<int, int>>> teleportPositions(26);9 10 for (int i = 0; i < matrix.size(); ++i)11 for (int j = 0; j < matrix[0].size(); ++j)12 if (matrix[i][j] != '.' && matrix[i][j] != '#')13 teleportPositions[matrix[i][j] - 'A'].emplace_back(i, j);14 15 return dijkstra(matrix, teleportPositions, {0, 0},16 {matrix.size() - 1, matrix[0].size() - 1});17 }18 19 private:20 int dijkstra(const vector<string>& matrix,21 const vector<vector<pair<int, int>>>& teleportPositions,22 const pair<int, int>& src, const pair<int, int>& dst) {23 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};24 const int m = matrix.size();25 const int n = matrix[0].size();26 vector<vector<int>> dist(m, vector<int>(n, INT_MAX));27 vector<bool> seen(26);28 29 dist[0][0] = 0;30 using T = pair<int, pair<int, int>>; 31 priority_queue<T, vector<T>, greater<>> minHeap;32 minHeap.push({dist[0][0], src});33 34 while (!minHeap.empty()) {35 const auto [d, u] = minHeap.top();36 minHeap.pop();37 if (u == dst)38 return d;39 const auto [i, j] = u;40 if (d > dist[i][j])41 continue;42 const char c = matrix[i][j];43 if (isupper(c) && !seen[c - 'A']) {44 seen[c - 'A'] = true;45 for (const auto& [x, y] : teleportPositions[c - 'A'])46 if (d < dist[x][y]) {47 dist[x][y] = d;48 minHeap.push({d, {x, y}});49 }50 }51 for (const auto& [dx, dy] : kDirs) {52 const int x = i + dx;53 const int y = j + dy;54 if (x < 0 || x == m || y < 0 || y == n)55 continue;56 if (matrix[x][y] == '#')57 continue;58 if (d + 1 < dist[x][y]) {59 dist[x][y] = d + 1;60 minHeap.push({d + 1, {x, y}});61 }62 }63 }64 65 return -1;66 }67};68