- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements