Questions:
1. to clockwise, or to counter-clockwise?
2. is it required to rotate the array in-place or allowed to copy to a new array?
Logic:
1. Rotate Layer-by-layer.
2. In each layer, rotate element-by-element.
3. We need a extra variable to save the previous value.
Source codes:
void Rotate(int [][] arr, int N)
{
for (int layer=0; layer < N/2; layer++)
{
first = layer;
last = N - layer;
for (int pos = first; pos < last; pos++)
{
//offset is calculated from the back
offset = pos - first;
//copy top left
top = arr[first][pos];
//then copy bottom left to top left
arr[first][pos] = arr[last-offset][first];
//then copy bottom right to bottom left
arr[last-offset][first] = arr[last][last-offset];
//then copy top right to bottom right
arr[last][last-offset] = arr[pos][last];
//finally copy saved top left to top right
arr[pos][last] = top;
}
}
return;
}
本文介绍了一种二维数组的旋转算法,通过逐层遍历并依次移动元素的方式实现矩阵的顺时针旋转。该方法适用于原地操作,无需额外的空间开销。
640

被折叠的 条评论
为什么被折叠?



