Find paths from corner cell to middle cell in maze
Given an n x n maze (where n is odd), find all paths from any corner cell to the center cell (n/2, n/2). From cell (i, j), you must move exactly maze[i][j] steps in one of the four cardinal directions (up, down, left, right). You cannot revisit a cell in the same path.
Example 1:
Input: maze = [
[3, 5, 4, 4, 7],
[3, 1, 3, 3, 1],
[3, 2, 3, 1, 2],
[6, 3, 1, 5, 3],
[1, 2, 3, 4, 1]
]
Output: One valid path from (0,0): (0,0) → (0,3) → (0,7 invalid)...
The paths vary; the goal is to reach (2,2) from corners.
Example 2:
Input: maze = [
[2, 1, 3],
[1, 1, 1],
[3, 1, 2]
]
Output: Paths from (0,0) to (1,1): (0,0)→(0,2)→(0,2 can't, bounds)
Edge cases: No valid path exists from a given corner. Maze with size 1 — the corner is the center.
- 1 <= n <= 9
- n is odd
Approach: DFS Backtracking
Start DFS from each corner cell. At each cell, try jumping exactly maze[i][j] steps in all four directions. Mark cells as visited to avoid cycles, and backtrack when a direction leads nowhere. Collect the path when you reach the center.
function findPaths(maze) {
const n = maze.length;
const mid = Math.floor(n / 2);
const results = [];
const corners = [[0, 0], [0, n - 1], [n - 1, 0], [n - 1, n - 1]];
const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];
function dfs(r, c, path, visited) {
if (r === mid && c === mid) {
results.push([...path]);
return;
}
const steps = maze[r][c];
for (const [dr, dc] of dirs) {
const nr = r + dr * steps;
const nc = c + dc * steps;
if (nr < 0 || nr >= n || nc < 0 || nc >= n) continue;
const key = nr * n + nc;
if (visited.has(key)) continue;
visited.add(key);
path.push([nr, nc]);
dfs(nr, nc, path, visited);
path.pop();
visited.delete(key);
}
}
for (const [sr, sc] of corners) {
const key = sr * n + sc;
dfs(sr, sc, [[sr, sc]], new Set([key]));
}
return results;
}
Time Complexity: O(4^(n²)) worst case — each cell has up to 4 choices, but visited pruning keeps it manageable
Space Complexity: O(n²) for the visited set and recursion stack
Saved in this browser only. Private to you.