15,798,592 members
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
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

## Solution 2

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;
}```

## Solution 1

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

v5
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.