Approach
Depth-first search
For The Maze III, 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
- 41 lines of Java from the credited upstream file 499.java.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 String findShortestWay(int[][] maze, int[] ball, int[] hole) {3 dfs(maze, ball[0], ball[1], hole, 0, 0, 0, "");4 return ans;5 }6 7 private String ans = "impossible";8 private int minSteps = Integer.MAX_VALUE;9 10 private void dfs(int[][] maze, int i, int j, int[] hole, int dx, int dy, int steps,11 final String path) {12 if (steps >= minSteps)13 return;14 15 if (dx != 0 || dy != 0) { 16 while (i + dx >= 0 && i + dx < maze.length && j + dy >= 0 && j + dy < maze[0].length &&17 maze[i + dx][j + dy] != 1) {18 i += dx;19 j += dy;20 ++steps;21 if (i == hole[0] && j == hole[1] && steps < minSteps) {22 minSteps = steps;23 ans = path;24 }25 }26 }27 28 if (maze[i][j] == 0 || steps + 2 < maze[i][j]) {29 maze[i][j] = steps + 2; 30 if (dx == 0)31 dfs(maze, i, j, hole, 1, 0, steps, path + "d");32 if (dy == 0)33 dfs(maze, i, j, hole, 0, -1, steps, path + "l");34 if (dy == 0)35 dfs(maze, i, j, hole, 0, 1, steps, path + "r");36 if (dx == 0)37 dfs(maze, i, j, hole, -1, 0, steps, path + "u");38 }39 }40}41