# 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.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+xx, p+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

184 Views 