原题
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?
代码实现
算法思想:
时间复杂度O(n^2),空间复杂度O(1)
public class Solution
{
//This is in-place algorithm by setting a cache cell
// first dividing layers(n>>1)
// second each layer element moves forward each(n-2*i-1) steps
public void Rotate(int[,] matrix)
{
int n = matrix.GetUpperBound(0) + 1;
int loop = n >> 1;
for (int i = 0; i < loop; i++){
int each = n - 2 * i - 1;
for (int k = 0; k < each; k++) {
for (int j = k + each; j < each * 4; j += each){
int cache;
if (j / each == 0) {//top
cache = matrix[i, i + j % each];
matrix[i, i + j % each] = matrix[i, i + k];
}
else if (j / each == 1) {//right
cache = matrix[i + j % each, n - i - 1];
matrix[i + j % each, n - i - 1] = matrix[i, i + k];
}
else if (j / each == 2) {//bottom
cache = matrix[n - i - 1, n - j % each - i - 1];
matrix[n - i - 1, n - j % each - i - 1] = matrix[i, i + k];
}
else {//left
cache = matrix[n - j % each - i - 1, i];
matrix[n - j % each - i - 1, i] = matrix[i, i + k];
}
//matrix[i,i+k]作为缓存区
matrix[i, i + k] = cache;
}
}
}
}
}