Last Updated: 12 Apr, 2022

Ninja And Matrix

Easy
Asked in companies
PhonePeVir Softech

Problem statement

Ninja loves patterns and visuals and recently he learned about 2-dimensional matrices now he wants to use his pattern skills on it. He has been provided with a 2-dimensional matrix with a size of ‘N’x’N’ and he wants to print the matrix in a snake pattern. Formally speaking he wants to print every odd indexed row in reverse order(0-indexed) and even indexed row as it is on a single line.

EXAMPLE:
Input: 'N' = 2, ‘MAT’ = [[1, 2], [5, 6]]

Output: 1 2 6 5

 So the first row will be printed as it is and the second row will be printed in reverse order.
Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

For each test case, the first line will contain a single integer 'N', the size of the matrix ‘Mat’, and then the next ‘N’ lines will contain ‘N’ integers representing the matrix elements.
Output format :
For each test case, print the matrix in a specified manner on a new line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 10
1 <= 'N' <= 10^3
1 <= ‘MAT[i]’ <= 10^9

Time Limit: 1 sec

Approaches

01 Approach

For each row, if the row is oddly indexed(0-indexed) then print it in reverse order or you can reverse the row, and then you can print it.

 

Algorithm :  

 

  • Initialize a vector named ‘ANS’.
  • For each row from 0 <= row <= ‘N’-1:-
    • If row %2 = 1 :-
      • Reverse the current row.
    • Push every element of the current row into vector ‘ANS’.
  • Return vector ‘ANS’.