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] ];
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
because the longest line starts from arr[0][1] and extends diagonally to -
arr[2][3]
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));
The output in the console will be-
3
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!