Issue
I am using the below code to rotate a NxN matrix by 90 degrees to the left. But it has some logical error. Most of the elements have rotated, but some haven't still. Please help me correct the code.
int n = 4, x = 1, i, j, temp;
int a[][] = new int[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i][j] = x++;
}
}
for (i = 0; i < n / 2; i++) {
for (j = n - 1; j >= n / 2; j--) {
temp = a[i][j];
a[i][j] = a[n - 1 - i][j];
a[n - 1 - i][j] = a[j][i];
a[j][i] = a[i][n - 1 - j];
a[i][n - 1 - j] = temp;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
Solution
I have modified your program a little bit and now it works. I have provided codes for rotating the matrix by 90 degrees on left as well as right. Have a look.
for (i = 0; i < n / 2; i++) {
for (j = i; j < n - 1 - i; j++) {
//Rotating left by 90 degrees
temp = a[i][j];
a[i][j] = a[j][n - 1 - i];
a[j][n - 1 - i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[n - 1 - j][i];
a[n - 1 - j][i] = temp;
/*
//Rotating right by 90 degrees
temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
*/
}
}
Answered By - h8pathak
Answer Checked By - Terry (JavaFixing Volunteer)