let inputMatrix = [
[1, 0, 0, 0],
[1, 1, 0, 1],
[1, 1, 0, 0],
[0, 1, 1, 1],
];
let visitedArray = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
];
const pathsArray = [];
const solveMaze = (n, inputMatrix) => {
if (inputMatrix[0][0] === 0) {
return pathsArray;
}
if (inputMatrix[n - 1][n - 1] === 0) {
return pathsArray;
}
solveMazeRun(0, 0, (pathMap = ""), visitedArray, n, inputMatrix);
console.log(pathsArray);
};
const solveMazeRun = (i, j, path, visitedArray, n, inputMatrix) => {
if (!isSafeToMove(i, j, n)) {
return false;
}
if (inputMatrix[i][j] === 0) {
return false;
}
if (visitedArray[i][j] === 1) {
return false;
}
if (n - 1 === i && n - 1 === j) {
pathsArray.push(path);
return false;
}
visitedArray[i][j] = 1;
solveMazeRun(i + 1, j, path + "D", visitedArray, n, inputMatrix);
solveMazeRun(i - 1, j, path + "L", visitedArray, n, inputMatrix);
solveMazeRun(i, j + 1, path + "R", visitedArray, n, inputMatrix);
solveMazeRun(i, j - 1, path + "U", visitedArray, n, inputMatrix);
visitedArray[i][j] = 0;
};
const isSafeToMove = (i, j, n) => {
if (i >= n || j >= n || i < 0 || j < 0) {
return false;
}
return true;
};
console.log(solveMaze(4, inputMatrix));
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)