给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。

说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
示例 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

一开始偷了个懒,直接把矩阵复制一下,然后按照转换的顺序写入原矩阵。。。但是题目说了必须在原地。。。

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();//行数
        vector<vector<int>> tempMatrix = matrix;//复制
        for (int row = 0; row < n; ++row){//按照修改后的顺序写入原矩阵
            for (int col = 0; col < n; ++col){
                matrix[col][n - row - 1] = tempMatrix[row][col];
            }
        }
    }
};

LeeCode 旋转图像
仔细观察一下旋转90°的效果会发现和先转换再镜像的效果一样。
方法二:

class Solution {
public:
	void rotate(vector<vector<int>>& matrix) {
		int n = matrix.size();//行数
		for (int row = 0; row < n - 1; ++row){//先进行转置
			for (int col = row + 1; col < n; ++col){
				swap(matrix[row][col], matrix[col][row]);
			}
		}
		for (int row = 0; row < n; ++row){//再进行水平镜像翻转
			for (int col = 0; col < n / 2; ++col){
				swap(matrix[row][col], matrix[row][n - col - 1]);
			}
		}
	}
};

LeeCode 旋转图像
方法三:逐圈进行旋转。
LeeCode 旋转图像

class Solution {
public:
	void rotate(vector<vector<int>>& matrix) {
		int n = matrix.size();//行数
		for (int depth = 0; depth < n / 2; ++depth){//圈数
			for (int begin = depth; begin < n - depth - 1; ++begin){//每圈从左到右
				int tempValue = matrix[depth][begin];
				matrix[depth][begin] = matrix[n - begin - 1][depth];
				matrix[n - begin - 1][depth] = matrix[n - depth - 1][n - begin - 1];
				matrix[n - depth - 1][n - begin - 1] = matrix[begin][n - depth - 1];
				matrix[begin][n - depth - 1] = tempValue;
			}
		}
	}
};

LeeCode 旋转图像
这种算法的关键就是,原地旋转矩阵,调换元素需要一起调换四个,当你向调换一个,其他三个需要安装规则同时旋转。斟酌斟酌。

相关文章: