Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Print Matrix in Z form
A Z-form traversal of a square matrix follows a specific pattern: traverse the first row, then the main diagonal (excluding elements already printed), and finally the last row. This creates a Z-like path through the matrix.
Understanding Z-Form Pattern
For a matrix of size n×n, Z-form traversal involves three steps ?
- Print all elements of the first row
- Print diagonal elements from top-right to bottom-left (excluding corners)
- Print all elements of the last row
Implementation
Here's how to implement Z-form matrix traversal ?
def print_z_form(matrix):
n = len(matrix)
# Print first row
for j in range(n):
print(matrix[0][j], end=' ')
# Print diagonal elements (excluding first and last row)
for i in range(1, n-1):
diagonal_col = n - 1 - i
print(matrix[i][diagonal_col], end=' ')
# Print last row (if more than one row)
if n > 1:
for j in range(n):
print(matrix[n-1][j], end=' ')
# Example matrix
arr = [[1, 2, 6, 9],
[1, 2, 3, 1],
[7, 1, 3, 5],
[1, 8, 7, 5]]
print("Matrix in Z-form:")
print_z_form(arr)
Matrix in Z-form: 1 2 6 9 3 1 1 8 7 5
Step-by-Step Breakdown
Let's trace through the algorithm with our 4×4 matrix ?
matrix = [[1, 2, 6, 9],
[1, 2, 3, 1],
[7, 1, 3, 5],
[1, 8, 7, 5]]
n = len(matrix)
print("Step 1 - First row:")
for j in range(n):
print(f"matrix[0][{j}] = {matrix[0][j]}")
print("\nStep 2 - Diagonal elements:")
for i in range(1, n-1):
diagonal_col = n - 1 - i
print(f"matrix[{i}][{diagonal_col}] = {matrix[i][diagonal_col]}")
print("\nStep 3 - Last row:")
for j in range(n):
print(f"matrix[{n-1}][{j}] = {matrix[n-1][j]}")
Step 1 - First row: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 6 matrix[0][3] = 9 Step 2 - Diagonal elements: matrix[1][2] = 3 matrix[2][1] = 1 Step 3 - Last row: matrix[3][0] = 1 matrix[3][1] = 8 matrix[3][2] = 7 matrix[3][3] = 5
Alternative Approach
Here's a more concise version using a single loop ?
def print_z_form_compact(matrix):
n = len(matrix)
result = []
# Collect all Z-form elements
# First row
result.extend(matrix[0])
# Diagonal elements (middle rows)
for i in range(1, n-1):
result.append(matrix[i][n-1-i])
# Last row (if matrix has more than 1 row)
if n > 1:
result.extend(matrix[n-1])
return result
# Test with example
arr = [[1, 2, 6, 9],
[1, 2, 3, 1],
[7, 1, 3, 5],
[1, 8, 7, 5]]
z_elements = print_z_form_compact(arr)
print("Z-form elements:", z_elements)
Z-form elements: [1, 2, 6, 9, 3, 1, 1, 8, 7, 5]
Conclusion
Z-form matrix traversal prints the first row, diagonal elements from top-right to bottom-left, and the last row. This creates a Z-shaped path through the matrix, useful for specific data processing patterns.
Advertisements
