C - matrix rotation

I'm writing a program in C and I need a M x N matrix to rotate clockwise. I tried some algorithms, but they only work in N x N matrices.

The matrix {(1,4), (2,5), (3,6)} should become {(3,2,1), (6,5,4)}:

1 4
2 5  ->  3 2 1
3 6      6 5 4

I wrote this piece of code to transpose the matrix, and now I don't know how to swap the columns:

void transpose(int matrix[MAX][MAX], int m, int n)
{
    int transpose[MAX][MAX], d, c;

    for (c = 0; c < m; c++)
      for( d = 0 ; d < n ; d++)
         transpose[d][c] = matrix[c][d];

    for (c = 0; c < n; c++)
        for(d = 0; d < m; d++)
            matrix[c][d] = transpose[c][d];
}

Upvotes: 0

Views: 4975

Answers (1)

Anindya Dutta
Anindya Dutta

Reputation: 1982

Here's an idea. I've implemented it in Java, but it should work in the same manner in C. The idea is to read the array row major wise from the end, and fill the other array column major wise, from the beginning.

    int a[][]={{1,4},{2,5},{3,6}};
    int m=3,n=2;   //you will need to edit this and actually calculate rows and columns.

    int b[][]=new int[n][m];

    for(int i=m-1; i>=0; i--)
      for(int j=0; j<n; j++)
        b[j][m-i-1]=a[i][j];


    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++)
           System.out.print(b[i][j]+"\t");
        System.out.println();
    }

Output at: https://ideone.com/TveuB5

Upvotes: 3

Related Questions