Print matrix elements from top | Java program for the above approach ; Function to traverse the matrix diagonally upwards ; Stores the maximum size of vector from all row of matrix nums [ ] [ ] ; Store elements in desired order ; Store every element on the basis of sum of index ( i + j ) ; Print the stored result ; Print in reverse order ; Driver Code ; Given vector of vectors arr ; Function Call
import java . util . * ; class GFG { static void printDiagonalTraversal ( int [ ] [ ] nums ) { int max_size = nums [ 0 ] . length ; ArrayList < ArrayList < Integer > > v = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < 2 * max_size - 1 ; i ++ ) { v . add ( new ArrayList < Integer > ( ) ) ; } for ( int i = 0 ; i < nums [ 0 ] . length ; i ++ ) { for ( int j = 0 ; j < nums [ 0 ] . length ; j ++ ) { v . get ( i + j ) . add ( nums [ i ] [ j ] ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = v . get ( i ) . size ( ) - 1 ; j >= 0 ; j -- ) { System . out . print ( v . get ( i ) . get ( j ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; } }