Rotating a 2D pixel array by 90 degrees

This can be done without using any extra space, so called In-place matrix transposition (not exact the same). Remember to do some mirroring after the transposition.

  1. If the image is square

    enter image description here

  2. If the image is not square

    • For non-square matrices, the algorithms are more complicated. Many of the algorithms prior to 1980 could be described as "follow-the-cycles" algorithms. That is, they loop over the cycles, moving the data from one location to the next in the cycle. In pseudocode form:

    enter image description here


You have old_data[rows][cols] and new_data[cols][rows], then:

for(int i=0; i<cols; i++) {
    for(int j=0; j<rows; j++) {
        new_data[i][j] = old_data[rows-1-j][i];
    }
}

This should rotate old_data by 90 degrees CW.


If you want to do it in-place with O(1) space, you can follow this:

  1. Transpose the matrix by swapping data[i][j] and data[j][i] :

    for (int i = 0; i < n; i += 1) {
        for (int j = i+1; j < n; j += 1) {
            swap(data[i][j], data[j][i]);
        }
    }
    
  2. Reverse each row or column for +90 or -90 degrees of rotation, respectively. For example for +90 degrees of rotation:

    for (int i = 0; i < n; i += 1) {
        for (int j = 0; j < n/2; j += 1) {
            swap(data[i][j], data[i][n-1-j]);
        }
    }