Print matrix elements from top | C ++ 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 ; Reverse all sublist ; Driver code ; Given vector of vectors arr ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printDiagonalTraversal ( vector < vector < int > > & nums ) { int max_size = nums . size ( ) ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { if ( max_size < nums [ i ] . size ( ) ) { max_size = nums [ i ] . size ( ) ; } } vector < vector < int > > v ( 2 * max_size - 1 ) ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { for ( int j = 0 ; j < nums [ i ] . size ( ) ; j ++ ) { v [ i + j ] . push_back ( nums [ i ] [ j ] ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { reverse ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) cout << v [ i ] [ j ] << " ▁ " ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; return 0 ; }