*27K*
Given a 2D matrix of N X N. Write a Java program to rotate the matrix in a clockwise direction by 90 degrees. The 0th row of the given matrix will be transformed to the nth column, the 1st row will be transformed to the n-1 column, and so on. Below is its representation.

To solve this problem, we will first find the transpose of the matrix and then reverse the elements of each row. This will result in a matrix rotated in a clockwise direction by 90 degrees.

The transpose of a matrix is a new matrix whose rows are the columns of the original.

One thing to be noted here is the nested loop that is starting with i. To understand the reason, you can refer the image at the end of the article.

Below is the Java program for the same.

public class Matrix {
public static void rotateMatrix(int[][] matrix){
int row = matrix.length;
//first find the transpose of the matrix.
for (int i = 0; i < row; i++){
for (int j = i; j < row; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//reverse each row
for (int i = 0; i< row; i++){
for(int j = 0; j< row/2; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][row - 1 - j];
matrix[i][row - 1 - j] = temp;
}
}
}

Below is the main method that will start the execution and print the resultant matrix.

public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Matrix.rotateMatrix(matrix);
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

## Explanation