# Write a program in Java to rotate a matrix by 90 degrees in anticlockwise direction

Let’s suppose we have given a square matrix of N×N. The task is to rotate the matrix counterclockwise. For example,

Input-1

N = 3
matrix[ ][ ] = [
[1 2 3],
[4 5 6],
[7 8 9]
]

Output

3 6 9 2 5 8 1 4 7

Explanation: After rotating the matrix counterclockwise it will generate the output as, 3 6 9 2 5 8 1 4 7.

## Approach to solve this problem

Initially the idea is to find the transpose of the given matrix and then swap each of the elements of the matrix while traversing row-wise.

• Take Input of a square matrix.

• Find the transpose of the matrix.

• Swap the element at index 0 with index n-1.

• Return the output.

## Example

import java.io.*;
class Solution {
static void rotateMatrix(
int n, int matrix[][]){
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp= matrix[i][j];
matrix[i][j]= matrix[j][i];
matrix[j][i]= temp;
}
}
for(int i=0;i<n;i++){
int top=0;
int bottom = n-1;
while(top<bottom){
int temp = matrix[top][i];
matrix[top][i]=matrix[bottom][i];
matrix[bottom][i] = temp;
top++;
bottom--;
}
}
}
static void displayMatrix(int N, int mat[][]){
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + mat[i][j]);
System.out.print("\n");
}
System.out.print("\n");
}
public static void main(String[] args){
int N = 3;
int mat[][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}

## Output

Running the above code will generate the output as,

3 6 9 2 5 8 1 4 7