DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Rat in a Maze - is possible path available?

This solution is for only 1 path & with connected cell track.

For Multiple hops allowed follow - Rat In A Maze - With Multiple Hops

let solutionMatrix = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
];
let N = solutionMatrix.length; // rows
let M = solutionMatrix[0]?.length; // column

let inputMatrix = [
  [1, 0, 0, 0],
  [1, 1, 0, 1],
  [1, 1, 0, 0],
  [0, 1, 1, 1],
];

const solveMaze = (solutionMatrix) => {
  if (solveMazeRun(0, 0) === false) {
    return false;
  } else {
    return solutionMatrix;
  }
};

const solveMazeRun = (i, j) => {
  if (N - 1 === i && M - 1 === j) {
    solutionMatrix[i][j] = 1;
    return true;
  }

  if (isSafeToMove(i, j)) {
    solutionMatrix[i][j] = 1;
    if (solveMazeRun(i + 1, j) === true) {
      return true;
    } else if (solveMazeRun(i, j + 1) === true) {
      return true;
    } else if (solveMazeRun(i - 1, j) === true) {
      return true;
    } else if (solveMazeRun(i, j - 1) === true) {
      return true;
    }
    solutionMatrix[i][j] = 0;
    return false;
  }
};

const isSafeToMove = (i, j) => {
  if (i < N && j < M && inputMatrix[i][j] !== 0) return true;
  else return false;
};

console.log(solveMaze(solutionMatrix));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)