Approach
Depth-first search
For The Maze II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 44 lines of C++ from the credited upstream file 505-2.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 int shortestDistance(vector<vector<int>>& maze, vector<int>& start,4 vector<int>& destination) {5 vector<vector<int>> dist(maze.size(), vector<int>(maze[0].size(), INT_MAX));6 dist[start[0]][start[1]] = 0;7 8 dfs(maze, dist, start[0], start[1], destination);9 10 return dist[destination[0]][destination[1]] == INT_MAX11 ? -112 : dist[destination[0]][destination[1]];13 }14 15 private:16 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};17 18 void dfs(vector<vector<int>>& maze, vector<vector<int>>& dist, int i, int j,19 const vector<int>& destination) {20 if (i == destination[0] && j == destination[1])21 return;22 23 for (const auto& [dx, dy] : kDirs) {24 int x = i;25 int y = j;26 int step = dist[i][j];27 while (isValid(maze, x + dx, y + dy)) {28 x += dx;29 y += dy;30 ++step;31 }32 if (step < dist[x][y]) {33 dist[x][y] = step;34 dfs(maze, dist, x, y, destination);35 }36 }37 }38 39 bool isValid(const vector<vector<int>>& maze, int x, int y) {40 return x >= 0 && x < maze.size() && y >= 0 && y < maze[0].size() &&41 maze[x][y] == 0;42 }43};44