Finding longest line of 1s in a matrix in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose, we have a binary matrix (an array of array that contains only 0 or 1) like this −

const arr = [
   [0,1,1,0],
   [0,1,1,0],
   [0,0,0,1]
];

We are required to write a JavaScript function that takes in one such matrix as the first and the only argument.

The task of our function is to find the longest line of consecutive ones in the matrix and return the count of 1s in it. The line could be horizontal, vertical, diagonal or anti-diagonal.

For example, for the above array, the output should be −

const output = 3

because the longest line is the one that starts from arr[0][1] and spans diagonally upto −

arr[2][3]

Example

The code for this will be −

 Live Demo

const arr = [
   [0,1,1,0],
   [0,1,1,0],
   [0,0,0,1]
];
const longestLine = (arr = []) => {
   if(!arr.length){
      return 0;
   }
   let rows = arr.length, cols = arr[0].length;
   let res = 0;
   const dp = Array(rows).fill([]);
   dp.forEach((el, ind) => {
      dp[ind] = Array(cols).fill([]);
      dp[ind].forEach((undefined, subInd) => {
         dp[ind][subInd] = Array(4).fill(null);
      });
   });
   for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
         if (arr[i][j] == 1) {
            dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
            dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
            dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
            dp[i][j][3] = (i > 0 && j < cols - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
            res = Math.max(res, Math.max(dp[i][j][0], dp[i][j][1]));
            res = Math.max(res, Math.max(dp[i][j][2], dp[i][j][3]));
         };
      };
   };
   return res;
};
console.log(longestLine(arr));

Output

And the output in the console will be −

3
raja
Published on 03-Mar-2021 05:29:48
Advertisements