VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-print-matrix-z-form/

⇱ Program to Print Matrix in Z form - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to Print Matrix in Z form

Last Updated : 16 Feb, 2023

Given a square matrix of order n*n, we need to print elements of the matrix in Z form

  Input: [[4, 5, 6, 8], 
 [1, 2, 3, 1], 
 [7, 8, 9, 4], 
 [1, 8, 7, 5]]
 
  Output: 4 5 6 8
 3
 8
 1 8 7 5
 
  Input: [[4, 5, 6, 8, 5],
 [1, 2, 3, 1, 4],
 [7, 8, 9, 4, 7],
 [1, 8, 7, 5, 2],
 [7, 9, 5, 6, 9],
 [9, 4, 5, 6, 6]]
 
  Output: 4 5 6 8 5
 1
 9
 8
 7
 9 4 5 6 6

👁 https://media.geeksforgeeks.org/wp-content/uploads/Capture-16.png

We need to traverse the first row of the matrix then the second diagonal and then the last row.

Implementation:


Output
4 5 6 8 3 8 1 8 7 5 

Time Complexity: O(n)
Auxiliary Space: O(1)

Alternatively, we can print first row and second diagonal except last element and then last row.


Output
4 5 6 8 3 8 1 8 7 5 

Time Complexity: O(n)
Auxiliary Space: O(1)

Alternate Simpler Implementation: 

Thanks to Aathishithan for suggesting this.

Implementation:


Output
4 5 6 8 3 8 1 8 7 5 

Time Complexity: O(n*n)
Auxiliary Space: O(1)

Comment
Article Tags: