/*
问题描述:给定一个2维数组,将数组中的元素旋转90度,空间复杂度为O(1)
来源:网易算法课
日期:2017-10-23
*/
问题描述:给定一个2维数组,将数组中的元素旋转90度,空间复杂度为O(1)
来源:网易算法课
日期:2017-10-23
*/
#include <iostream>
using namespace std;
class ArrayRotation{
public:
ArrayRotation(int n)
{
size = n;
arr = new int *[n];
for (int i = 0; i < n; i++)
arr[i] = new int[n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
arr[i][j] = i*n + j + 1;
}
top = 0;
right = n - 1;
bottom = n - 1;
left = 0;
top_mov = left;
right_mov = top;
bottom_mov = right;
left_mov = bottom;
}
void printArray()
{
while (top < bottom && left < right)
{
top_val = arr[top][top_mov];
right_val = arr[right_mov][right];
bottom_val = arr[bottom][bottom_mov];
left_val = arr[left_mov][left];
arr[top][top_mov] = left_val;
arr[right_mov][right] = top_val;
arr[bottom][bottom_mov] = right_val;
arr[left_mov][left] = bottom_val;
top_mov++;
right_mov++;
bottom_mov--;
left_mov--;
if (top_mov >= right)
{
top++;
right--;
bottom--;
left++;
top_mov = left;
right_mov = top;
bottom_mov = right;
left_mov = bottom;
}
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
private:
int **arr;
int top, left, right, bottom;
int top_mov, left_mov, right_mov, bottom_mov;
int top_val, left_val, right_val, bottom_val;
int size;
};
int main()
{
ArrayRotation ar(4);
ar.printArray();
return 0;
}