Approach
Breadth-first search
For The Maze, 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
- 40 lines of C++ from the credited upstream file 490.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 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.
1class Solution {2 public:3 bool hasPath(vector<vector<int>>& maze, vector<int>& start,4 vector<int>& destination) {5 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};6 const int m = maze.size();7 const int n = maze[0].size();8 queue<pair<int, int>> q{{{start[0], start[1]}}};9 vector<vector<bool>> seen(m, vector<bool>(n));10 seen[start[0]][start[1]] = true;11 12 while (!q.empty()) {13 const auto [i, j] = q.front();14 q.pop();15 for (const auto& [dx, dy] : kDirs) {16 int x = i;17 int y = j;18 while (isValid(maze, x + dx, y + dy)) {19 x += dx;20 y += dy;21 }22 if (x == destination[0] && y == destination[1])23 return true;24 if (seen[x][y])25 continue;26 q.emplace(x, y);27 seen[x][y] = true;28 }29 }30 31 return false;32 }33 34 private:35 bool isValid(const vector<vector<int>>& maze, int x, int y) {36 return 0 <= x && x < maze.size() && 0 <= y && y < maze[0].size() &&37 maze[x][y] == 0;38 }39};40