Longest path in 2-D that contains increasing sequence in JavaScript

JavascriptWeb DevelopmentFront End Technology

Increasing Sequence

A sequence of numbers in which each succeeding element is either greater or equal to the preceding element is an increasing sequence.

For instance,

4, 6, 8, 9, 11, 14 is increasing sequence
3, 3, 3, 3, 3, 3, 3 is also an increasing sequence

Problem:

We are required to write a JavaScript function that takes in a 2-D array of numbers, arr, as the only argument. Our function should find and return the length of that longest path in the array that contains only increasing numbers.

For example, if the input to the function is −

const arr = [
   [4, 5, 6],
   [4, 3, 7],
   [3, 3, 2]
];

Then the output should be −

const output = 4;

Output Explanation:

Because the longest increasing sequence is 4, 5, 6, 7.

Example

The code for this will be −

const arr = [
   [4, 5, 6],
   [4, 3, 7],
   [3, 3, 2]
];
const longestIncreasingPath = (arr = []) => {
   let longest = 0;
   let dp = Array(arr.length).fill(null).map(() =>
   Array(arr[0].length).fill(1));
   const backtracking = (row, col) => {
      if (dp[row][col]!=1) return dp[row][col];
      let dRow = [1,0,-1,0];
      let dCol = [0,1,0,-1];
      for (let i = 0;i<dRow.length;i++) {
         let nR = row + dRow[i], nC = col+dCol[i];
         if (nR >= 0 && nR < arr.length && nC >= 0 && nC < arr[0].length && arr[nR][nC] > arr[row][col]) {
            dp[row][col] = Math.max(dp[row][col], 1 + backtracking(nR, nC))
         };
      };
      return dp[row][col];
   }
   for (let i=0;i<arr.length;i++) {
      for (let j=0;j<arr[0].length;j++) {
         longest = Math.max(longest, backtracking(i, j));
      };
   };
   return longest;
};
console.log(longestIncreasingPath(arr));

Code Explanation:

The Idea

  • Here, we have used backtracking depth first search.

  • The recursion function simply returns the longest increasing path for a given row and column

  • If we already have a record of the longest increasing path for a position, then we can simply return that.

Output

And the output in the console will be −

4
raja
Published on 19-Mar-2021 06:11:51
Advertisements