1

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");
}
Community
  • 1
  • 1
TheHardRock
  • 691
  • 7
  • 17

3 Answers3

1

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;
        */
    }
}
Community
  • 1
  • 1
h8pathak
  • 1,342
  • 3
  • 17
  • 29
0

It looks as though you were trying to use the code from this SO question, but it didn't work. I transcripted the answer verbatim (AFAIK) into Java. I don't know what direction you want to rotate but maybe this will help you.

int n = 4;
int a[][] = new int[n][n];
int f = Math.floor((double)n/2);
int c = Math.ceil((double)n/2);

for (int x=0; x < f; ++x) {
    for (int y=0; y < c; ++y) {
        int temp = a[x,y];
        a[x, y] = a[y, n-1-x];
        a[y, n-1-x] = a[n-1-x, n-1-y];
        a[n-1-x, n-1-y] = a[n-1-y, x];
        a[n-1-y, x] = temp;
    }
}
Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Another variant for rotating 90 degrees by left, this solution is only dealing with int. It also cares for odd dimension values.

int dim = 5;
int a[][] = new int[dim][dim];
int floor = dim / 2;
int ceil = (dim + 1) / 2;

for (int row = 0; row < floor; row++) {
    for (int col = 0; col < ceil; col++) {
        int oppRow = dim - row - 1;
        int oppCol = dim - col - 1;
        int temp = a[row][col];
        a[row][col] = a[col][oppRow];
        a[col][oppRow] = a[oppRow][oppCol];
        a[oppRow][oppCol] = a[oppCol][row];
        a[oppCol][row] = temp;
    }
}