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
- 40 lines of Python from the credited upstream file 499.py.
- 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 def findShortestWay(3 self,4 maze: list[list[int]],5 ball: list[int],6 hole: list[int],7 ) -> str:8 ans = 'impossible'9 minSteps = math.inf10 11 def dfs(i: int, j: int, dx: int, dy: int, steps: int, path: str):12 nonlocal ans13 nonlocal minSteps14 if steps >= minSteps:15 return16 17 if dx != 0 or dy != 0: 18 while (0 <= i + dx < len(maze) and 0 <= j + dy < len(maze[0]) and19 maze[i + dx][j + dy] != 1):20 i += dx21 j += dy22 steps += 123 if i == hole[0] and j == hole[1] and steps < minSteps:24 minSteps = steps25 ans = path26 27 if maze[i][j] == 0 or steps + 2 < maze[i][j]:28 maze[i][j] = steps + 2 29 if dx == 0:30 dfs(i, j, 1, 0, steps, path + 'd')31 if dy == 0:32 dfs(i, j, 0, -1, steps, path + 'l')33 if dy == 0:34 dfs(i, j, 0, 1, steps, path + 'r')35 if dx == 0:36 dfs(i, j, -1, 0, steps, path + 'u')37 38 dfs(ball[0], ball[1], 0, 0, 0, '')39 return ans40