在JavaScript矩阵中对角线遍历

问题:

我们需要编写一个JavaScript函数,该函数采用一个方矩阵(具有相同行数和列数的数组的数组)。函数应该对角地遍历该数组数组,并准备一个新的元素数组,并按照在遍历时遇到的顺序进行放置。

例如,如果函数的输入为-

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

那么输出应该是-

const output = [1, 2, 4, 7, 5, 3, 6, 8, 9];

示例

为此的代码将是-

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const findDiagonalOrder = (arr = []) => {
   if(!arr.length){
      return [];
   };
   let ind = 0;
   let colBegin = 0, rowBegin = 0;
   let rowMax = arr.length, colMax = arr[0].length;
   const res = [], stack = [];
   while(rowBegin< rowMax || colBegin<colMax) {
      for(let row = rowBegin, col = colBegin; row < rowMax && col >=0 ;
      row++,col--){
         if(ind%2 === 0){
            stack.push((arr[row][col]));
         }else{
            res.push(arr[row][col]);
         };
      };
      ind++;
      while(stack.length){
         res.push(stack.pop());
      };
      colBegin++
      if(colBegin> colMax-1 && rowBegin < rowMax){
         colBegin = colMax-1
         rowBegin++
      }
   };
   return res
};
console.log(findDiagonalOrder(arr));

代码说明:

我们采取的步骤是-

  • 在一个方向上移动,跟踪起点。

  • 如果index是偶数,我们将压入堆栈并在到达对角线末端时弹出,然后将popd添加到我们的输出数组中。

  • 当我们移到下一个对角线时,我们保持索引递增。

  • 我们递增列的开始索引,直到到达终点为止,因为它在下一次迭代中将在最后一个索引处停止,并且我们将从此点开始递增行开始的索引。

输出结果

控制台中的输出将是-

[
   1, 2, 4, 7, 5,
   3, 6, 8, 9
]