作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnhhkv/ 来源:力扣(LeetCode)
题目描述:
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ]答案v1.0
class Solution { public: void rotate(vector<vector<int>> &matrix) { int n = matrix.size(); // 按圈遍历数组 for (int cnt = 0; cnt < matrix.size() / 2; cnt++) { for (int time = 0; time < n - 1; time++) { //上 //坐标重新写。 int pre = matrix[cnt][cnt]; for (int i = 1; i < n; i++) { int temp = matrix[cnt][i + cnt]; matrix[cnt][i + cnt] = pre; pre = temp; } // 右 for (int i = 1; i < n; i++) { int temp = matrix[i + cnt][n - 1 + cnt]; matrix[i + cnt][n - 1 + cnt] = pre; pre = temp; } // 下 for (int i = 1; i < n; i++) { int temp = matrix[n - 1 + cnt][n - 1 - i + cnt]; matrix[n - 1 + cnt][n - 1 - i + cnt] = pre; pre = temp; } // 左 for (int i = 1; i < n; i++) { int temp = matrix[n - 1 - i + cnt][cnt]; matrix[n - 1 - i + cnt][cnt] = pre; pre = temp; } } n -= 2; } } };