![]() |
VOOZH | about |
Given a square matrix of order n × n, the task is to print its elements in Z form that is, print the first row, then the opposite diagonal (from top-right to bottom-left), and finally the last row of the matrix. For Example:
Input: [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
Output: 1 2 3 5 7 8 9
Let's explore different methods to print the matrix in Z form in Python.
This method uses NumPy’s advanced indexing to directly extract the first row, reverse diagonal, and last row in a single optimized line without explicit loops.
4 5 6 8 3 8 1 8 7 5
Explanation:
This approach combines rows and diagonals in a single list using list comprehension. It collects all required elements in order and prints them together fast and clean without extra loops.
4 5 6 8 3 8 1 8 7 5
Explanation:
This method flattens the matrix into a single list and computes exact indices for the top row, diagonal, and bottom row, then prints those elements sequentially.
4 5 6 8 3 8 1 8 7 5
Explanation:
This method uses nested loops to traverse each required position step by step first printing the top row, then the diagonal, and finally the bottom row in order.
4 5 6 8 3 8 1 8 7 5
Explanation:
Please refer complete article on Program to Print Matrix in Z form for more details!