Array Rotating的解题

本文介绍了一种二维数组的旋转算法,通过逐层遍历并依次移动元素的方式实现矩阵的顺时针旋转。该方法适用于原地操作,无需额外的空间开销。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值