Web Toolbar by Wibiya

Pages

Sunday, January 8, 2012

Rotate a matrix by 90 degrees.

Solution #1: Rotation of a matrix by a certain angle (+90, -90, +180, -180) can be done by a combination of basic operations like transpose, column swapping and row swapping. For example, to rotate a matrix by +90 degrees just transpose it and then swap the columns. Rest of the rotations can be done using a similar approach. Below is the code for +90 degrees rotation,

#define N 5

void printMatrix(int mat[N][N])
{
    int i=0;
    int j=0;

    for(i=0; i < N; i++)
    {
        for(j=0; j < N; j++)
            printf("%d ", mat[i][j]);

        printf("\n");
    }
}

void initMatrix(int mat[N][N])
{
    int i=0;
    int j=0;

    srand(time(NULL));
    for(i=0; i < N; i++)
        for(j=0; j < N; j++)
            mat[i][j] = rand() % 10;
}

void transpose(int mat[N][N])
{
    int i=0;
    int j=0;

    for(i=0; i < N; i++)
    {
        for(j=i; j < N; j++)
        {
            int temp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = temp;
        }
    }
}

void swapCol(int mat[N][N])
{
    int i=0;
    int j=0;

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

int main()
{
    int matrix[N][N] = {0, };

    //initialize and print matrix
    initMatrix(matrix);
    printMatrix(matrix);
    
    printf("\n");

    //transpose and swap columns to rotate by +90
    transpose(matrix);
    swapCol(matrix);

    printMatrix(matrix);
    
}

2 comments:

Unknown said...

Thanks for the ideas and code. Though, wouldn't a +90 be counter clockwise, and -90 the way your code is working?

Kinshuk Chandra said...

Beautiful and clear code. Really liked it. I have also written a similar post here - http://k2code.blogspot.in/2014/03/rotate-n-n-matrix-by-90-degrees.html.