假设我们有一个像这样的二进制矩阵(仅包含0或1的数组的数组)-
const arr = [ [0,1,1,0], [0,1,1,0], [0,0,0,1] ];
我们需要编写一个JavaScript函数,该函数采用一个矩阵作为第一个和唯一的参数。
我们函数的任务是在矩阵中找到最长的连续行并返回1的计数。该线可以是水平,垂直,对角线或反对角线。
例如,对于上述数组,输出应为-
const output = 3
因为最长的线是从arr [0] [1]开始并斜跨至-
arr[2][3]
为此的代码将是-
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));输出结果
控制台中的输出将是-
3