Approach
Breadth-first search
For Shortest Path 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
- 75 lines of C++ from the credited upstream file 1778.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 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 * void std::move(char direction);8 * boolean isTarget();9 * };10 */11 12enum class Grid { kUnvisited, kStart, kTarget, kBlocked, kEmpty };13 14class Solution {15 public:16 int findShortestPath(GridMaster& master) {17 constexpr int m = 501;18 constexpr int startX = m;19 constexpr int startY = m;20 vector<vector<Grid>> grid(m * 2, vector<Grid>(m * 2, Grid::kUnvisited));21 22 23 dfs(master, grid, startX, startY);24 25 queue<pair<int, int>> q{{{startX, startY}}};26 grid[startX][startY] = Grid::kBlocked;27 28 29 for (int step = 1; !q.empty(); ++step)30 for (int sz = q.size(); sz > 0; --sz) {31 const auto [i, j] = q.front();32 q.pop();33 for (const auto& [dx, dy] : kDirs) {34 const int x = i + dx;35 const int y = j + dy;36 if (grid[x][y] == Grid::kTarget)37 return step;38 if (grid[x][y] == Grid::kBlocked)39 continue;40 grid[x][y] = Grid::kBlocked;41 q.emplace(x, y);42 }43 }44 45 return -1;46 }47 48 private:49 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};50 static constexpr char charTable[4] = {'R', 'D', 'L', 'U'};51 52 void dfs(GridMaster& master, vector<vector<Grid>>& grid, int i, int j) {53 if (grid[i][j] != Grid::kUnvisited)54 return;55 if (master.isTarget())56 grid[i][j] = Grid::kTarget;57 else58 grid[i][j] = Grid::kEmpty;59 60 for (int k = 0; k < 4; ++k) {61 const int x = i + kDirs[k][0];62 const int y = j + kDirs[k][1];63 const char d = charTable[k];64 const char undoD = charTable[(k + 2) % 4];65 if (master.canMove(d)) {66 master.move(d);67 dfs(master, grid, x, y);68 master.move(undoD);69 } else {70 grid[x][y] = Grid::kBlocked;71 }72 }73 }74};75