Rotating a 2D Array by 90 Degrees (Java)

Implement a function that takes a square 2D array (# columns = # rows = n) and rotates it by 90 degrees. Do not create a separate 2D array for the rotation, it rotates in the 2D array.

Example:

int a1[][] = {{1, 2, 3},
              {4, 5, 6},
              {7, 8, 9}};
 // rotate(a1, 3) should return:
 // [[7, 4, 1],
 // [8, 5, 2],
 // [9, 6, 3]]

Example:

  int a2[][] = {{1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}};
 // rotate(a2, 4) should return:
 // [[13, 9, 5, 1],
 // [14, 10, 6, 2],
 // [15, 11, 7, 3],
 // [16, 12, 8, 4]]

To understand this problem, we need to analyze what is really going on in the rotation.

a. each element in the rotation is changing position with 3 other elements in the 2D array: a->b, b->c, c->d, d->a

 [?, a, ?, ?]  
 [?, ?, ?, b]
 [d, ?, ?, ?]
 [?, ?, c, ?]

If a={i,j}, then b={j,n-1-i}, c={n-1-i, n-1-j},d={n-1-j,i}

b. In each rotation happens in a “ring” (example, a1, a2, a2, b1, b2 ….d2, d2), we only swap the positions of n-2 elements in the first row. We do not swape n-1th element again because it is a duplicate (We swapped a1 with b1, and b1 does not need to be swapped again. So we only swap a1, a2, a3. ).

 [a1, a2, a3, b1]  
 [d3, ??, ??, b2]
 [d2, ??, ??, b3]
 [d1, c3, c2, c1]

So the outer loop should be for (int i=0; i < n-1; i++):

c. We swap the positions from the outside ring (1’s) to the inner rings (2’s). Each time the iteration decrements by 2 elements. At ith row, we swap from ith element to n-2-i th elements.

 [1, 1, 1, 1]  
 [1, 2, 2, 1]
 [1, 2, 2, 1]
 [1, 1, 1, 1]

So the inner loop is for (int j=i; j<n-1-i; j++)

Put everything together:

 public static int[][] rotate(int[][] a, int n) {

 for (int i=0; i< n-1; i++){
     for (int j=i; j<n-1-i; j++){
         int 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;
         }
     }
     return a;
     }
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s