Print matrix elements from top | Javascript program for the above approach ; Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the right neighbour if it exists ; Given vector of vectors arr ; Function call
class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } function printDiagonalTraversal ( nums ) { let m = nums . length ; let q = [ ] ; q . push ( new pair ( 0 , 0 ) ) ; while ( q . length != 0 ) { let p = q [ 0 ] ; q . shift ( ) ; document . write ( nums [ p . first ] [ p . second ] + " " ) ; if ( p . second == 0 && p . first + 1 < m ) { q . push ( new pair ( p . first + 1 , p . second ) ) ; } if ( p . second + 1 < nums [ p . first ] . length ) q . push ( new pair ( p . first , p . second + 1 ) ) ; } } let arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; printDiagonalTraversal ( arr ) ;