Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Matrix but will also help you build up problem-solving skills.

POTD 8 November: Print Matrix in snake Pattern
Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern.
Examples :
Input: mat[][] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
Output: 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32
Input: mat[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Output: 1 2 3 6 5 4 7 8 9
Approach: Follow the steps below to solve the problem:
- Traverse all rows.
- For every row, check if it is even or odd.
- If even, we print from left to right
- else print from right to left.
Below is the implementation of above approach:
class Solution {
public:
// Function to return list of integers visited in snake
// pattern in matrix.
vector<int> snakePattern(vector<vector<int> > matrix)
{
vector<int> ans;
int N = matrix.size();
int M = matrix[0].size();
// 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++)
ans.push_back(matrix[i][j]);
// If current row is odd, print from
// right to left
}
else {
for (int j = N - 1; j >= 0; j--)
ans.push_back(matrix[i][j]);
}
}
return ans;
}
};
class Solution {
// Function to return list of integers visited in snake
// pattern in matrix.
static ArrayList<Integer> snakePattern(int matrix[][])
{
ArrayList<Integer> ans = new ArrayList<>();
int N = matrix.length;
int M = matrix[0].length;
// Traverse through all rows
for (int i = 0; i < M; i++) {
// If the current row is even, print from left
// to right
if (i % 2 == 0) {
for (int j = 0; j < N; j++) {
ans.add(matrix[i][j]);
}
}
else { // If the current row is odd, print from
// right to left
for (int j = N - 1; j >= 0; j--) {
ans.add(matrix[i][j]);
}
}
}
return ans;
}
}
class Solution:
#Function to return list of integers visited in snake pattern in matrix.
def snakePattern(self, matrix):
ans = []
N = len(matrix)
M = len(matrix[0])
# Traverse through all rows
for i in range(M):
# If the current row is even, print from left to right
if i % 2 == 0:
for j in range(N):
ans.append(matrix[i][j])
else: # If the current row is odd, print from right to left
for j in range(N - 1, -1, -1):
ans.append(matrix[i][j])
return ans
Time Complexity: O(N x M), Traversing over all the elements of the matrix, therefore N X M elements are there.
Auxiliary Space: O(1)
