VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-matrix-elements-from-top-left-to-bottom-right-in-diagonally-upward-manner/

⇱ Diagonal Traversal of a Matrix II - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Diagonal Traversal of a Matrix II

Last Updated : 23 Jul, 2025

Given a vectors of vectors arr[], the task is to print the elements of arr[] in the diagonally upwards order as illustrated below.

Examples: 

Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Output: 1 4 2 7 5 3 8 6 9
Explanation:
Below is the illustration of how diagonally upward order is printed:

👁 Image

Input: arr[][] = {{1, 2, 3, 4, 5}, {6, 7}, {8}, {9, 10, 11}, {12, 13, 14, 15, 16}}
Output: 1 6 28 7 3 9 4 12 10 5 13 11 14 15 16
Explanation:
Below is the illustration of how diagonally upward order is printed:

👁 Image

Approach: The idea is based on the observation that all elements in a particular upward diagonal have a sum equal to the (row index + column index). Follow the steps to solve the problem:

  • Initialize a vector of vectors v to store the elements in the desired format.
  • Iterate over the matrix arr[][] using variables i and j and for each i and j push arr[i][j] to v[i + j].
  • After the above steps, reverse every row in the v.
  • Now, print all elements in stored in v row-wise to get the desired result.

Below is the implementation of the above approach: 


Output: 
1 4 2 7 5 3 8 6 9

 

Time Complexity: O(N*M), where N is the size of the given matrix and M is maximum size of any row in the matrix.
Auxiliary Space: O(N*M)

Alternate Approach: The above problem can be also be solved by using queue. Follow the steps to solve the problem:

  • Initialize a queue Q, and insert the index of the first cell of arr[][], i.e., (0, 0).
  • Initialize a vector v to store the elements in the desired format.
  • While q is not empty, do the following:
    • Pop the element at front of the queue and push it in v. 
    • Push the index of the current cell just below it, only if the current cell is the first in its row.
    • Push the index of its right neighbor cell if it exists.
  • After the above steps, print all elements stored in v.

Below is the implementation of the above approach:


Output: 
1 4 2 7 5 3 8 6 9

 

Time Complexity: O(N*M), where N is the size of the given matrix and M is maximum size of any row in the matrix.
Auxiliary Space: O(N)


 


 


 

Comment
Article Tags:
Article Tags: