xxxxxxxxxx
const maze2 = [
["S", "0"],
["0", "E"],
];
const maze3 = [
["S", "0", "0"],
["0", "0", "0"],
["0", "0", "E"],
];
const maze4 = [
["S", "0", "0", "0"],
["0", "0", "0", "0"],
["0", "0", "0", "0"],
["0", "0", "0", "E"],
];
const maze5 = [
["S", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "E"],
];
const maze6 = [
["S", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "E"],
];
// https://lietcode.hashnode.dev/find-all-paths-in-a-maze
function findPathsInMaze(maze) {
const rows = maze.length;
const cols = maze[0].length;
const paths = [];
// Helper function for backtracking
function backtrack(row, col, path) {
// Base case: if out of bounds or hits a wall
if (
row < 0 ||
col < 0 ||
row >= rows ||
col >= cols ||
maze[row][col] === "1"
) {
return;
}
// Base case: if the endpoint is reached
if (maze[row][col] === "E") {
path.push([row, col]);
paths.push([path]);
path.pop();
return;
}
// Mark the cell as part of the path
const temp = maze[row][col];
maze[row][col] = "1"; // Mark as visited
path.push([row, col]);
// Explore the four possible directions
backtrack(row + 1, col, path); // Move down
backtrack(row - 1, col, path); // Move up
backtrack(row, col + 1, path); // Move right
backtrack(row, col - 1, path); // Move left
// Unmark the cell (backtrack step)
maze[row][col] = temp;
path.pop();
}
// Start backtracking from the starting point
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (maze[i][j] === "S") {
backtrack(i, j, []);
break;
}
}
}
return paths;
}