- codewithshiva

Latest

Search Bar

Tuesday, July 6, 2021

 Circular Traversal

Description

Given a square matrix, you have to find the reverse U traversal of the matrix. Refer the sample I/O for better understanding. Refer the given figure for better understanding.

Note: No element should be visited more than once.

Image

Input

The first line of the input contains T, the number of test cases.

The next line contains N, the size of the square matrix.

The next N lines contains N space separated integers each denoting the values of the matrix.

Constraints

1 <= T <= 10

1 <= N <= 50

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

Output

For each test case, print the elements that lie on the reverse U traversal, 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 2 3 6 9 8 

Hint

The elements that lie on the circular traversal of the given matrix are - 7,4,1,2,3,6,9,8

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int testno = sc.nextInt();


        for (int i =0 ; i<testno;i++){

            int size = sc.nextInt();

            int [][]arrsize = new int[size][size];


            //Feeding values

            for (int j =0 ; j<size;j++){

                for (int k =0 ; k<size;k++){

                    arrsize[j][k]=sc.nextInt();

                }

            }//Ending Array feeding

            if (arrsize.length==1) {

                System.out.print(arrsize[0][0]);

            }else {

                for (int j =0 ; j<size;j++){

                    System.out.print(arrsize[size-1-j][0]+" ");

                }

                for (int j =0 ; j<size;j++){

                    if (j!=0 && j!=size-1){

                        System.out.print(arrsize[0][j]+" ");

                    }


                }

                for (int j =0 ; j<size;j++){

                    System.out.print(arrsize[j][size-1]+" ");

                }

                for (int j =0 ; j<size;j++){

                    if (j!=0 && j!=size-1){

                        if (j!=size-2){

                            System.out.print(arrsize[size-1][size-j-1]+" ");

                        }else {

                            System.out.print(arrsize[size-1][size-j-1]);

                        }


                    }

            }

            }System.out.println();

        }


    }

}


No comments:

Post a Comment