N traversal From 2d array in java - codewithshiva

Latest

Search Bar

Friday, July 2, 2021

N traversal From 2d array in java

 Extract N traversal elements From 2D Array

Description

You are given a matrix of size n x n. Find the 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

7 4 1 5 9 6 3 


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[size-1-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[j][k]+" ");
}
}
}

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

}

}

No comments:

Post a Comment