Print matrix elements from top | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printDiagonalTraversal ( vector < vector < int > > & nums ) { int m = nums . size ( ) ; queue < pair < int , int > > q ; q . push ( { 0 , 0 } ) ; while ( ! q . empty ( ) ) { pair < int , int > p = q . front ( ) ; q . pop ( ) ; cout << nums [ p . first ] [ p . second ] << " ▁ " ; if ( p . second == 0 && p . first + 1 < m ) { q . push ( { p . first + 1 , p . second } ) ; } if ( p . second + 1 < nums [ p . first ] . size ( ) ) q . push ( { p . first , p . second + 1 } ) ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; return 0 ; }