Home > Web Front-end > JS Tutorial > Find the longest row of consecutive 1's in a matrix in JavaScript

Find the longest row of consecutive 1's in a matrix in JavaScript

王林
Release: 2023-09-21 17:37:17
forward
1368 people have browsed it

Find the longest row of consecutive 1s in a matrix in JavaScript

Suppose we have a binary matrix (an array containing only arrays of 0 or 1) as shown below -

const arr = [
   [0,1,1,0],
   [0,1,1,0],
   [0,0,0,1]
];
Copy after login

We need to write a JavaScript function that The function accepts such a matrix as the first and only parameter.

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

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

const output = 3
Copy after login

because the longest line starts from arr[0][1] and extends diagonally to -

arr[2][3]
Copy after login

Example

The code is -

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));
Copy after login

Output

The output in the console will be-

3
Copy after login

The above is the detailed content of Find the longest row of consecutive 1's in a matrix in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template