Finding all the unique paths in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 11-Dec-2020 13:39:11
Advertisements