ans
ans

Reputation: 390

Rotating matrix by 90*n degrees CW

I know that algorithm to rotate matrix by 90 degrees CW:

for (int i=0; i<N/2; ++i)
    for (int j=0; j<(N+1)/2; ++j)
        {
            int c = A[i][j];
            A[i][j] = A[N-j-1][i];
            A[N-j-1][i] = A[N-i-1][N-j-1];
            A[N-i-1][N-j-1] = A[j][N-i-1];
            A[j][N-i-1] = c;
        }

Do I need (and can I?) to modify that algorithm or can I just do it n times to rotate matrix by 90*n degrees (where n belongs Z (integer))?

Upvotes: 0

Views: 138

Answers (1)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

2x rotate is a flip which is faster. 3x rotate is reverse rotate which is faster. 4x rotate is itself and fastest. So you can use modulus operation.

Let f be an array of functions.

if(n>=0)
    f[n%4]();
else
    f[4-(-n)%4]();

where

f[0]=itself();
f[1]=rotate_cw();
f[2]=flip();
f[3]=rotate_ccw();

Upvotes: 1

Related Questions