數組旋轉

/*
問題描述:給定一個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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章