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
Python program to print matrix in a snake pattern
In this article, we will learn how to print a matrix in a snake pattern. A snake pattern prints the first row left to right, the second row right to left, the third row left to right, and so on, creating a zigzag or snake-like traversal.
We will explore two different approaches to accomplish this task using Python.
What is a Snake Pattern?
Given a matrix, the snake pattern traversal means:
Print even-indexed rows (0, 2, 4...) from left to right
Print odd-indexed rows (1, 3, 5...) from right to left
For example, a 3×3 matrix would be traversed as: 1?2?3, 6?5?4, 7?8?9.
Method 1: Using Nested For Loop
This approach checks if the row index is even or odd and prints accordingly ?
def printSnakePattern(matrix):
rows = len(matrix)
columns = len(matrix[0])
for i in range(rows):
if i % 2 == 0: # Even row - left to right
for j in range(columns):
print(matrix[i][j], end=" ")
else: # Odd row - right to left
for j in range(columns - 1, -1, -1):
print(matrix[i][j], end=" ")
# Input matrix
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
print("Given Matrix:")
for row in matrix:
print(row)
print("\nSnake Pattern:")
printSnakePattern(matrix)
Given Matrix: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] Snake Pattern: 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13
Method 2: Using Slicing to Reverse Alternate Rows
This method reverses odd-indexed rows using Python's slice notation [::-1] before printing ?
def printSnakePatternSlicing(matrix):
rows = len(matrix)
columns = len(matrix[0])
# Create a copy to avoid modifying original matrix
temp_matrix = [row[:] for row in matrix]
# Reverse alternate rows (odd-indexed rows)
for i in range(rows):
if i % 2 != 0:
temp_matrix[i] = temp_matrix[i][::-1]
# Print the modified matrix
for i in range(rows):
for j in range(columns):
print(temp_matrix[i][j], end=" ")
# Input matrix
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
print("Given Matrix:")
for row in matrix:
print(row)
print("\nSnake Pattern:")
printSnakePatternSlicing(matrix)
Given Matrix: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] Snake Pattern: 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13
Comparison
| Method | Space Complexity | Modifies Original | Best For |
|---|---|---|---|
| Nested Loop | O(1) | No | Memory efficiency |
| Slicing | O(n×m) | No (with copy) | Code readability |
Conclusion
Both methods effectively print a matrix in snake pattern. The nested loop approach is more memory-efficient, while the slicing method offers cleaner code. Choose based on your requirements for memory usage and code readability.
