Traversing Diagonally in a matrix in JavaScript


Problem:

We are required to write a JavaScript function that takes in a square matrix (an array of arrays having the same number of rows and columns). The function should traverse diagonally through that array of array and prepare a new array of elements placed in that order it encountered while traversing.

For example, if the input to the function is −

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

Then the output should be −

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

Example

 Live Demo

The code for this will be −

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));

Code Explanation:

The steps we took are −

  • Traversed in one direction keeping track of starting point.

  • If index is even, we'll push to a stack and pop once it reaches end of diagonal, adding popped to our output array.

  • We keep incrementing index as we move to next diagonal.

  • We increment column begin index until it reaches end, as it for the next iterations it will be stopped at last index and we'll be incrementing row begin index moving from this point.

Output

And the output in the console will be −

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

Updated on: 04-Mar-2021

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements