
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 All Unique Paths in JavaScript
Suppose we have an array of m * n order. A person starts at the start block of the 2-D array (0,0) and he wants to reach the end (m, n). The limitation is that at once, he can either move one step down or one step right.
We are required to write a JavaScript function that takes in the height and width of the 2-D grid.
The function should find out the number of unique paths that are available to the person to reach to the end.
Example
Following is the code −
const height = 3; const width = 4; const findUniquePath = (width = 1, height = 1) => { const board = Array(height).fill(null).map(() => { return Array(width).fill(0); }); for (let rowIndex = 0; rowIndex < height; rowIndex += 1) { for (let columnIndex = 0; columnIndex < width; columnIndex += 1) { if (rowIndex === 0 || columnIndex === 0) { board[rowIndex][columnIndex] = 1; } } } for (let rowIndex = 1; rowIndex < height; rowIndex += 1) { for (let columnIndex = 1; columnIndex < width; columnIndex += 1) { const uniquesFromTop = board[rowIndex - 1][columnIndex]; const uniquesFromLeft = board[rowIndex][columnIndex - 1]; board[rowIndex][columnIndex] = uniquesFromTop + uniquesFromLeft; } } return board[height - 1][width - 1]; }; console.log(findUniquePath(width, height));
Output
Following is the output on console −
10
Advertisements