在JavaScript中找到矩阵中最长的连续1的行

王林
王林 转载
2023-09-21 17:37:17 913浏览

在JavaScript中找到矩阵中最长的连续1的行

假设我们有一个二元矩阵(仅包含 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

以上就是在JavaScript中找到矩阵中最长的连续1的行的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除