题目
Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
标签
Array
难度
适中
分析
题目意思是给定一个n*n的矩阵,向右旋转90°C。我的做法是做两次变换,具体如下图所示,按照红色的对角线进行转换,最后得到想要的结果。
C代码实现
void rotate(int** matrix, int matrixRowSize, int matrixColSize) {
int i, j;
int temp = 0;
for (i = 0; i < matrixRowSize; i++)
{
for (j = i+1; j < matrixColSize; j++)
{
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (i = 0; i < matrixRowSize; i++)
{
for (j = 0; j < matrixColSize/2; j++)
{
temp = matrix[i][j];
matrix[i][j] = matrix[i][matrixColSize-j-1];
matrix[i][matrixColSize-j-1] = temp;
}
}
}