Approach
Depth-first search
For The Maze, 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
- 35 lines of Java from the credited upstream file 490-2.java.
- 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 boolean hasPath(int[][] maze, int[] start, int[] destination) {3 boolean[][] seen = new boolean[maze.length][maze[0].length];4 return dfs(maze, seen, start[0], start[1], destination);5 }6 7 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};8 9 private boolean dfs(int[][] maze, boolean[][] seen, int i, int j, int[] destination) {10 if (i == destination[0] && j == destination[1])11 return true;12 if (seen[i][j])13 return false;14 15 seen[i][j] = true;16 17 for (int[] dir : DIRS) {18 int x = i;19 int y = j;20 while (isValid(maze, x + dir[0], y + dir[1])) {21 x += dir[0];22 y += dir[1];23 }24 if (dfs(maze, seen, x, y, destination))25 return true;26 }27 28 return false;29 }30 31 private boolean isValid(int[][] maze, int x, int y) {32 return 0 <= x && x < maze.length && 0 <= y && y < maze[0].length && maze[x][y] == 0;33 }34}35