Print matrix in diagonal pattern | Javascript program to print matrix in diagonal order ; Initialize indices to traverse through the array ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = true traverse from bottom to top ; Set i and j according to direction ; If isUp = false then traverse from top to bottom ; Set i and j according to direction ; Inverse the value of isUp to change the direction ; function call
function printMatrixDiagonal ( arr , len ) { let i = 0 , j = 0 ; let isUp = true ; for ( let k = 0 ; k < len * len ; ) { if ( isUp ) { for ( ; i >= 0 && j < len ; i -- , j ++ ) { document . write ( arr [ i ] [ j ] + ' ' ) ; k ++ ; } if ( i < 0 && j < len ) i = 0 ; if ( j === len ) i = i + 2 , j -- ; } else { for ( ; j >= 0 && i < len ; i ++ , j -- ) { document . write ( arr [ i ] [ j ] + ' ' ) ; k ++ ; } if ( j < 0 && i < len ) j = 0 ; if ( i === len ) j = j + 2 , i -- ; } isUp = ! isUp } } let arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; let arrLength = arr . length ; printMatrixDiagonal ( arr , arrLength ) ;