Print matrix elements from top | Java 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 ; Driver Code ; Given vector of vectors arr ; Function call
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printDiagonalTraversal ( int [ ] [ ] nums ) { int m = nums . length ; Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( 0 , 0 ) ) ; while ( ! q . isEmpty ( ) ) { pair p = q . peek ( ) ; q . remove ( ) ; System . out . print ( nums [ p . first ] [ p . second ] + " ▁ " ) ; if ( p . second == 0 && p . first + 1 < m ) { q . add ( new pair ( p . first + 1 , p . second ) ) ; } if ( p . second + 1 < nums [ p . first ] . length ) q . add ( new pair ( p . first , p . second + 1 ) ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; } }