Approach
Breadth-first search
For Minimum Path Cost in a Hidden Grid, 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
- 79 lines of C++ from the credited upstream file 1810.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected, together with recursive traversal.
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.
1/**2 * 3 * 4 * class GridMaster {5 * public:6 * bool canMove(char direction);7 * int std::move(char direction);8 * boolean isTarget();9 * };10 */11 12class Solution {13 public:14 int findShortestPath(GridMaster& master) {15 constexpr int m = 100;16 constexpr int startX = m;17 constexpr int startY = m;18 vector<int> target{m * 2, m * 2};19 vector<vector<int>> grid(m * 2, vector<int>(m * 2, -1));20 vector<vector<bool>> seen(m * 2, vector<bool>(m * 2));21 22 23 dfs(master, grid, startX, startY, target);24 25 priority_queue<vector<int>, vector<vector<int>>, greater<>> minHeap;26 minHeap.push({0, startX, startY});27 28 29 while (!minHeap.empty()) {30 const vector<int> tuple = minHeap.top();31 const int cost = tuple[0];32 const int i = tuple[1];33 const int j = tuple[2];34 minHeap.pop();35 if (i == target[0] && j == target[1])36 return cost;37 if (seen[i][j])38 continue;39 seen[i][j] = true;40 for (const auto& [dx, dy] : kDirs) {41 const int x = i + dx;42 const int y = j + dy;43 if (x < 0 || x == 2 * m || y < 0 || y == 2 * m)44 continue;45 if (seen[x][y] || grid[x][y] == -1)46 continue;47 const int nextCost = cost + grid[x][y];48 minHeap.push({nextCost, x, y});49 }50 }51 52 return -1;53 }54 55 private:56 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};57 static constexpr char charTable[4] = {'R', 'D', 'L', 'U'};58 59 void dfs(GridMaster& master, vector<vector<int>>& grid, int i, int j,60 vector<int>& target) {61 if (master.isTarget()) {62 target[0] = i;63 target[1] = j;64 }65 66 for (int k = 0; k < 4; ++k) {67 const int x = i + kDirs[k][0];68 const int y = j + kDirs[k][1];69 const char d = charTable[k];70 const char undoD = charTable[(k + 2) % 4];71 if (master.canMove(d) && grid[x][y] == -1) {72 grid[x][y] = master.move(d);73 dfs(master, grid, x, y, target);74 master.move(undoD);75 }76 }77 }78};79