本文主要是介绍leetcode 刷题之路 34 Rotate Image,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
在不开辟新空间的前提下顺时针旋转一个矩阵。
90度顺时针旋转矩阵有这样的规律,以下面矩阵为例,观察旋转前后的矩阵,不难发现,7到了1的位置,1到了3的位置,3到了9的位置,9又到了7的位置,这几个数字沿着矩阵中心发生了旋转,仔细观察2,6,8,4也有同样的规律。
实际上,在矩阵发生90度顺时针旋转后,位于位置[i,j]的数字总是移动到了位置[j,n-1-i]。
利用这个规律,我们只需要一个临时变量,就可以完成矩阵的旋转。
测试通过程序:
class Solution {
public:void rotate(vector<vector<int> > &matrix) {int n=matrix.size();for(int i=0;i<n/2;i++)for(int j=i;j<n-i-1;j++){int temp=matrix[i][j];matrix[i][j]=matrix[n-j-1][i];matrix[n-j-1][i]=matrix[n-i-1][n-j-1];matrix[n-i-1][n-j-1]=matrix[j][n-i-1];matrix[j][n-i-1]=temp;}}
};
这篇关于leetcode 刷题之路 34 Rotate Image的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!