Printing Reverse N Traversal elements of a 2D Matrix of n*n elements - codewithshiva

Latest

Search Bar

Friday, July 2, 2021

Printing Reverse N Traversal elements of a 2D Matrix of n*n elements

 Reverse N Traversal Elements printing of n*n elements in a matrix

Description

You are given a matrix of size n x n. Find the Reverse Ntraversal of the matrix. Refer the following figure for better understanding.

Image

Input

The first line contains T, the number of test cases. The first line of each test case contains N, the size of the square matrix.

Next N lines contain N space separated integers, denoting the values of the matrix.


Constraints

1 <= T <= 10

1 <= N <= 500

1 <= A[i][j] <= 1000

Output

For each test case, print the N traversal of the matrix on a single line, on a new line.

Sample Input 1 

1
3
1 2 3
4 5 6
7 8 9

Sample Output 1

1 4 7 5 3 6 9 


import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();

//number of test
for (int i = 0;i<times;i++){
int size = sc.nextInt();

//declaring array
int [][]array = new int[size][size];

//entering array
for (int j =0;j<size;j++){
for (int k = 0 ; k <size;k++){
array[j][k] = sc.nextInt();
}
}

if (array.length==1){
System.out.println(array[0][0]);
}else {
//getting first pattern
for (int j =0;j<size;j++){
System.out.print(array[j][0]+" ");
}

for (int j =0;j<size;j++){
for (int k = 0 ; k <size;k++){
if(j==k && j!=0 && k!=size-1){
System.out.print(array[k][j]+" ");
}
}
}

//getting last patern
for (int j =0;j<size;j++){
System.out.print(array[j][size-1]+" ");
}
System.out.println();
}

}
}
}

No comments:

Post a Comment