POTD Solutions | 8 Nov’ 23 | Print Matrix in snake Pattern
Last Updated :
22 Nov, 2023
View all POTD Solutions
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.
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.
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:
C++
class Solution {
public :
vector< int > snakePattern(vector<vector< int > > matrix)
{
vector< int > ans;
int N = matrix.size();
int M = matrix[0].size();
for ( int i = 0; i < M; i++) {
if (i % 2 == 0) {
for ( int j = 0; j < N; j++)
ans.push_back(matrix[i][j]);
}
else {
for ( int j = N - 1; j >= 0; j--)
ans.push_back(matrix[i][j]);
}
}
return ans;
}
};
|
Java
class Solution {
static ArrayList<Integer> snakePattern( int matrix[][])
{
ArrayList<Integer> ans = new ArrayList<>();
int N = matrix.length;
int M = matrix[ 0 ].length;
for ( int i = 0 ; i < M; i++) {
if (i % 2 == 0 ) {
for ( int j = 0 ; j < N; j++) {
ans.add(matrix[i][j]);
}
}
else {
for ( int j = N - 1 ; j >= 0 ; j--) {
ans.add(matrix[i][j]);
}
}
}
return ans;
}
}
|
Python3
class Solution:
def snakePattern( self , matrix):
ans = []
N = len (matrix)
M = len (matrix[ 0 ])
for i in range (M):
if i % 2 = = 0 :
for j in range (N):
ans.append(matrix[i][j])
else :
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)
Share your thoughts in the comments
Please Login to comment...