矩阵旋转(含代码)

题目:

将一个n*n的矩阵顺时针旋转90度

思路有两种:假设n=5

第一种,我们可以看看每一个位置的元素原始位置和最终位置的坐标,寻找规律

像这样:(0,0)->(0,4);(0,1)->(1,4);(1,0)->(0,3);(1,1)->(1,3);所以我们可以得到如下规律:原来的列号变成了新位置的行号;原来的行号假设为row,变为n-1-row;
这种算法时间复杂度为O(n^2),空间复杂度也为O(n^2);代码这里就不写了,有兴趣的可以自己试试;

第二种,这种也是笔者一开始没有想到的,是在面试官提示下才总结出来的。

我们可以分层处理,观察元素位置的持续变化,像这样:

第一层: :

(0,0)->(0,4)->(4,4)->(4,0)->(0,0);
(0,1)->(1.4)->(4,3)->(3,0)->(0,1);
(0,2)->(2.4)->(4,2)->(2,0)->(0,2);
(0,3)->(3.4)->(4,1)->(1,0)->(0,3);
(0,4)->(4.4)->(4,0)->(0,0)->(0,4); //same as first line
第二层
(1,1)->(1.3)->(3,3)->(3,1)->(1,1);
(1,2)->(2.3)->(3,2)->(2,1)->(1,2);
(1,3)->(3.3)->(3,1)->(1,1)->(1,3)
;

所以我们只需要一个临时变量,就可以实现这种旋转,具体代码如下,仅供参考,欢迎拍砖:

#include <iostream>
#include <vector>
/*
	Program:
		rotate a n*n matrix by 90 degree clockwise
	tips:	
		suppose n=5;	
		first way: (0,0)->(0,4);(0,1)->(1,4);(1,0)->(0,3);(1,1)->(1,3);
				so we can conclude like this: original column changed to row, 
				original row changed to n-1-row
				
				time complexity:O(n^2); space complexity:O(n^2);
		second way: obviously we should handle this problem by deck, supposing the deck counts from outer  to inner,
				numbered from 0;
					first deck:
				(0,0)->(0,4)->(4,4)->(4,0)->(0,0);
				(0,1)->(1.4)->(4,3)->(3,0)->(0,1);
				(0,2)->(2.4)->(4,2)->(2,0)->(0,2);
				(0,3)->(3.4)->(4,1)->(1,0)->(0,3);
				(0,4)->(4.4)->(4,0)->(0,0)->(0,4); //same as first line
					second deck:
				(1,1)->(1.3)->(3,3)->(3,1)->(1,1);
				(1,2)->(2.3)->(3,2)->(2,1)->(1,2);
				(1,3)->(3.3)->(3,1)->(1,1)->(1,3);
				
				time complexity:O(n^2); space complexity:O(1);
*/
using namespace std;
void rotateMatrix(vector<vector<int> > &matrix);
void printMatrix(vector<vector<int> > &matrix);
int main()
{
	vector<vector<int> > matrix;
	for(int i=0;i<5;++i)
	{
		vector<int> temp;
		for(int j=0;j<5;++j)
		{
			temp.push_back(5*i+j+1);			
		}
		matrix.push_back(temp);		
	}
	cout<<"The original matrix is like: "<<endl;
	printMatrix(matrix);
	rotateMatrix(matrix);
	cout<<"Now the matrix changed like this: "<<endl; 
	printMatrix(matrix);
	return 0;
} 
void rotateMatrix(vector<vector<int> > &matrix)
{
	int n=matrix.size();
	
	/*handle the matrix by deck*/
	for(int deck=0;deck<n/2;++deck)
	{
		for(int i=0;i<n-2*deck-1;++i)
		{
			int temp(0);
			temp=matrix[deck][i+deck];
			matrix[deck][i+deck]=matrix[n-1-i-deck][deck];
			matrix[n-1-i-deck][deck]=matrix[n-1-deck][n-1-i-deck];
			matrix[n-1-deck][n-1-i-deck]=matrix[i+deck][n-1-deck];
			matrix[i+deck][n-1-deck]=temp;
		}
	}
}
void printMatrix(vector<vector<int> > &matrix)
{
	for(int i=0;i<5;++i)
	{
		for(int j=0;j<5;++j)
		{
			cout<<matrix[i][j]<<" ";
		}
		cout<<endl;
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值