Print matrix elements from top | 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
def printDiagonalTraversal ( nums ) : NEW_LINE INDENT m = len ( nums ) NEW_LINE q = [ ] NEW_LINE q . append ( [ 0 , 0 ] ) NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( 0 ) ; NEW_LINE print ( nums [ p [ 0 ] ] [ p [ 1 ] ] , end = " ▁ " ) NEW_LINE if ( p [ 1 ] == 0 and p [ 0 ] + 1 < m ) : NEW_LINE INDENT q . append ( [ p [ 0 ] + 1 , p [ 1 ] ] ) ; NEW_LINE DEDENT if ( p [ 1 ] + 1 < len ( nums [ p [ 0 ] ] ) ) : NEW_LINE INDENT q . append ( [ p [ 0 ] , p [ 1 ] + 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE printDiagonalTraversal ( arr ) ; NEW_LINE DEDENT