Problem solution · C++

Shortest Path in a Hidden Grid

Shortest Path in a Hidden Grid: a C++ solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
75 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeShortest Path in a Hidden Grid · C++C++
Use this to learn the idea, then write your own version.
/** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { *  public: *   bool canMove(char direction); *   void std::move(char direction); *   boolean isTarget(); * }; */ enum class Grid { kUnvisited, kStart, kTarget, kBlocked, kEmpty }; class Solution { public:  int findShortestPath(GridMaster& master) {    constexpr int m = 501;    constexpr int startX = m;    constexpr int startY = m;    vector<vector<Grid>> grid(m * 2, vector<Grid>(m * 2, Grid::kUnvisited));     // Build the grid information by DFS.    dfs(master, grid, startX, startY);     queue<pair<int, int>> q{{{startX, startY}}};    grid[startX][startY] = Grid::kBlocked;     // Find the steps by BFS.    for (int step = 1; !q.empty(); ++step)      for (int sz = q.size(); sz > 0; --sz) {        const auto [i, j] = q.front();        q.pop();        for (const auto& [dx, dy] : kDirs) {          const int x = i + dx;          const int y = j + dy;          if (grid[x][y] == Grid::kTarget)            return step;          if (grid[x][y] == Grid::kBlocked)            continue;          grid[x][y] = Grid::kBlocked;          q.emplace(x, y);        }      }     return -1;  }  private:  static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};  static constexpr char charTable[4] = {'R', 'D', 'L', 'U'};   void dfs(GridMaster& master, vector<vector<Grid>>& grid, int i, int j) {    if (grid[i][j] != Grid::kUnvisited)      return;    if (master.isTarget())      grid[i][j] = Grid::kTarget;    else      grid[i][j] = Grid::kEmpty;     for (int k = 0; k < 4; ++k) {      const int x = i + kDirs[k][0];      const int y = j + kDirs[k][1];      const char d = charTable[k];      const char undoD = charTable[(k + 2) % 4];      if (master.canMove(d)) {        master.move(d);        dfs(master, grid, x, y);        master.move(undoD);      } else {        grid[x][y] = Grid::kBlocked;      }    }  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗