problem no 60:(problem on the matrix):printing the matrix in snake pattern

 problem:

Print Matrix in snake Pattern
Basic Accuracy: 72.32% Submissions: 6635 Points: 1

Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern depicted below.

Example 1:

Input:
N = 3 
matrix[][] = {{45, 48, 54},
             {21, 89, 87}
             {70, 78, 15}}
Output: 45 48 54 87 89 21 70 78 15 
Explanation:
Matrix is as below:
45 48 54
21 89 87
70 78 15
Printing it in snake pattern will lead to 
the output as 45 48 54 87 89 21 70 78 15.

Example 2:

Input:
N = 2
matrix[][] = {{1, 2},
              {3, 4}}
Output: 1 2 4 3
Explanation:
Matrix is as below:
1 2 
3 4
Printing it in snake pattern will 
give output as 1 2 4 3.
 
code:
 vector<int> snakePattern(vector<vector<int> > matrix)
{
vector<int> result;

for(int i=0;i<matrix.size();i++)
{
if(i%2==0)
{
for(int j=0;j<matrix[i].size();j++)
{
result.push_back(matrix[i][j]);
}
}
else
{
for(int j=matrix[i].size()-1;j>=0;j--)
{
result.push_back(matrix[i][j]);
}
}


}

return result;
}

 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.