(Asked by MICROSOFT, PAYTM, SAMSUNG, AMAZON, SNAPDEAL…)
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Rotated the input matrix by
90 degrees in anti-clockwise direction.
Approach: The idea is to find the transpose of the matrix and then reverse the columns of the transposed matrix.
Solution:
Here’s the complete code.
package matrix;
import java.util.Scanner;
public class MatrixRotationAntiClockWise {
//transpose
static void transpose(int arr[][]) {
for(int i=0; i<arr.length; i++) {
for(int j=i; j<arr[0].length; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
static void reversedColoumns(int arr[][]) {
for(int i=0; i<arr[0].length; i++) {
for(int j = 0, k = arr[0].length-1; j < k; j++, k-- ) {
int temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- != 0) {
int n = sc.nextInt();
int arr[][] = new int[n][n];
for(int i=0; i<n; i++) {
for(int j=0; j< n; j++) {
arr[i][j] = sc.nextInt();
}
}
transpose(arr);
reversedColoumns(arr);
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
}
Input:
1
5
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
Output:
21 22 23 24 25
16 17 18 19 20
11 12 13 14 15
6 7 8 9 10
1 2 3 4 5
- Time complexity :O(Row*Column).
The matrix is traversed twice, so the complexity is O(Row*Column). - Space complexity :O(1).
The space complexity is constant as no extra space is required.
Hope you guys understand the solution of matrix rotation in anticlockwise by (90) in java.
For practicing the question link is given:https://practice.geeksforgeeks.org/problems/rotate-by-90-degree/0
Thanks for reading…!
Happy Coding..!
Thank You…!