Finding path to the end of maze using JavaScript


Problem

We are required to write a JavaScript function that takes in a matrix of N * N order. The walls in the matrix are marked by ‘W’ and empty positions are marked by ‘_’

We can move in any of the four directions at any point. Our function should return true if we can reach to the end [N - 1, N - 1], false otherwise.

Example

Following is the code −

 Live Demo

const maze = [
   ['_', 'W', 'W', 'W'],
   ['_', 'W', 'W', 'W'],
   ['W', '_', '_', 'W'],
   ['W', 'W', 'W', '_']
];
const canFindPath = (m = []) => {
   let h = m.length;
   let w = m[0].length;
   let queue = [[0, 0]];
   let mark = (xx, yy) => {
      [[1, 0], [-1, 0], [0, 1], [0, -1], [0, 0]].map(p => {
         let [x, y] = [p[0]+xx, p[1]+yy];
         if (0 <= x && x < w) {
            if (0 <= y && y < h) {
               if (m[y][x] === '.') {
                  m[y][x] = '#';
                  queue.push([x, y]);
               }
            }
         }
      });
   };
   do {
      let p = queue.shift();
      mark(...p);
   } while (queue.length);
   return m[h-1][w-1] !== '.';
};
console.log(canFindPath(maze));

Output

true

Updated on: 17-Apr-2021

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements