
Master Matrix Traversal: How to Print a Matrix in Snake Pattern (C++, Java, Python)
Are you prepping for technical interviews and need to sharpen your matrix manipulation skills? Do you want a simple way to traverse a 2D array in a unique, visually interesting way? This guide breaks down how to print a matrix in a snake pattern, complete with code examples in multiple languages.
Why Learn Snake Pattern Matrix Traversal?
Understanding matrix traversal is fundamental in computer science. The snake pattern offers a twist on traditional row-wise or column-wise methods. Here's why it's important:
- Algorithm Practice: It's a great exercise for improving logical thinking and coding skills.
- Interview Prep: Matrix-related questions are common in technical interviews.
- Versatility: The core concept can be adapted to solve various problems related to data processing and game development.
Understanding the Snake Pattern
The "snake pattern" refers to printing the elements of a matrix in a zig-zag fashion. You move left to right on even rows and right to left on odd rows.
- Start at the top-left corner.
- Print the first row from left to right.
- Print the second row from right to left.
- Continue alternating direction for each row.
Step-by-Step Approach
Here is a basic outline to achieve the snake pattern:
- Iterate through each row of the matrix.
- Check if the current row index is even or odd.
- If even, print the row from left to right.
- If odd, print the row from right to left.
Implementation in C++
Here's how you can implement the snake pattern in C++:
// C++ program to print matrix in snake order
#include <iostream>
#define M 4
#define N 4
using namespace std;
void print(int mat[M][N]) {
// Traverse through all rows
for (int i = 0; i < M; i++) {
// If current row is even, print from left to right
if (i % 2 == 0) {
for (int j = 0; j < N; j++)
cout << mat[i][j] << " ";
}
// If current row is odd, print from right to left
else {
for (int j = N - 1; j >= 0; j--)
cout << mat[i][j] << " ";
}
}
}
// Driver code
int main() {
int mat[M][N] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
print(mat);
return 0;
}
Implementation in Java
Here's the Java equivalent:
Implementation in Python3
And here's the Python version:
Time and Space Complexity
- Time Complexity: O(N * M), where N is the number of rows and M is the number of columns. This is because we need to traverse each element in the matrix.
- Auxiliary Space: O(1) as it uses a constant amount of extra space.
Key Takeaways
- Matrix traversal in a snake pattern involves alternating the direction of printing elements in each row.
- The core logic relies on checking whether the row index is even or odd.
- This pattern can be implemented easily in multiple programming languages with similar time and space complexities.
By understanding and implementing this pattern, you enhance your problem-solving skills and become better prepared for technical interviews.