Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello , i'm struggling to find an algorithm that will rotate a matrix (multidimensional array) 90 degrees clockwise. I cant use any functions (transcope etc), Basically i need to write the code on my own. Any tips?


thanks!
Posted
Comments
Legor 17-Dec-14 3:25am    
What datatype are you using as a matrice?
Daniel Mashukov 17-Dec-14 3:37am    
Int
Legor 18-Dec-14 3:20am    
No i mean how is your matrice defined? E.g. is it a vector of vectors or a 2D array like a[100][100] ?
Daniel Mashukov 19-Dec-14 2:31am    
2D array

C#
for (int i = 0; i < rows; i++)
    {
        for (int j = i + 1; j < col; j++)
        {
            temp = arr[i][j];
            arr[i][j] = arr[j][i];
            arr[j][i] = temp;
        }
    }

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < col / 2; j++)
        {
            temp = arr[i][j];
            arr[i][j] = arr[i][col - 1 - j];
            arr[i][col - 1 - j] = temp;
        }
 
Share this answer
 
Try something like this
suppose matrice a of size (n x m)
C++
for(int i=0; i<n;i++)
{
    for(int j=m-1; j>=0;j--)
    {
        printf("%d ", a[j][i]);  //in C
        cout<<a[j][i];          //in C++
    }
    printf("\n"); or  //cout<<endl;
}

if you want to save it to other matrix:
Take another matrix, say b of size (n x m)
C++
int x = 0;
for(int i=0; i<n;i++)
{
    for(int j=m-1; j>=0;j--)
    {
        printf("%d ", a[j][i]);  //in C
        cout<<a[j][i];          //in C++
        b[i][x++] = a[j][i]; 
    }
    x = 0;
    printf("\n"); or  //cout<<endl;
}



if you matrix is
1 2
3 4
it will return
3 1
4 2
 
Share this answer
 
v5
Comments
Legor 18-Dec-14 3:23am    
That doesnt rotate the matrice but just prints out the inverse.
Member 10641779 19-Dec-14 1:12am    
No, This will not print inverse.
Daniel Mashukov 19-Dec-14 2:32am    
It does prints the rotated matrix but you are right, it doesn't change the matrix itself.
Member 10641779 24-Dec-14 4:10am    
I added the code to save it to another matrix.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900