Square matrix clockwise rotation of the implementation code
- 2020-04-01 23:27:04
- OfStack
For example, the following square matrix:
1
2
3
4
5
6
7
8
9 10 11 12
13 14 15 16
Clockwise rotation, but the following results:
13
9
5
1
10 of 14
6
2
15 11
7
3
16 12
8
4
#include <stdio.h>
void rotate(int* x, int rank)
{
int* y = (int*)malloc(sizeof(int) * rank * rank);
for(int i=0; i<rank * rank; i++)
{
//Analysis with the original first line & NBSP; The number of rows becomes the same column & PI; Take the original first column and make it the same row. & have spent (I %rank)*rank turns a column into a row & cake; & have spent Rank -(I /rank)-1) makes the row a column
y[(i%rank)*rank+(rank-(i/rank)-1) ] = x[i];
}
for(i=0; i<rank*rank; i++)
{
x[i] = y[i];
}
free(y);
}
int main(int argc, char* argv[])
{
int x[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int rank = 4;
rotate(&x[0][0], rank);
for(int i=0; i<rank; i++)
{
for(int j=0; j<rank; j++)
{
printf("%4d", x[i][j]);
}
printf("n");
}
return 0;
}