Company:Microsoft
Question:
Given an square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.
Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two lines. The first line of each test case consists of an integer N, where N is the size of the square matrix.The second line of each test case contains NxN space separated values of the matrix M.
Output:
Corresponding to each test case, in a new line, print the rotated array.
Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 50
Example:
1 ≤ N ≤ 50
Example:
Input
1
3
1 2 3 4 5 6 7 8 9
1
3
1 2 3 4 5 6 7 8 9
Output
3 6 9 2 5 8 1 4 7
3 6 9 2 5 8 1 4 7
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int m =sc.nextInt();
for(int mi=0;mi<m;mi++){
int n = sc.nextInt();
int [][]matrix= new int[n][n];
for(int row=0;row<n;row++){
for(int col=0;col<n;col++){
matrix[row][col]=sc.nextInt();
}
}
rotateMatrix(matrix,n);
displayMatrix(matrix);
}
}
public static void rotateMatrix(int [][]matrix,int n){
for(int i=0;i<n/2;i++){
for(int j=i;j<n-1-i;j++){
//x(i),xy(i,j),y(j)
int temp= matrix[i][j];
matrix[i][j]=matrix[j][n-1-i];
matrix[j][n-1-i]=matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j]=matrix[n-1-j][i];
matrix[n-1-j][i]=temp;
}
}
}
public static void displayMatrix(int[][]matrix){
for(int i1=0;i1<matrix.length;i1++){
for(int j1=0;j1<matrix.length;j1++){
System.out.print(matrix[i1][j1]+" ");
}
}
System.out.println();
}
}
Execution Time: 0.54
Comments
Post a Comment