DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Rat In a Maze - Get All Possible Paths

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));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)