48. Rotate Image

leetcode链接

题目

给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。

代码

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        for(int i = 0; i < n/2; i++){//多少圈
            for(int j = 0; j < n-1-2*i; j++){//每圈多少次
                vector<int> rows = {i, n-1-i-j, n-1-i, i+j};
                vector<int> cols = {i+j, i, n-1-i-j, n-1-i};
                int tmp = matrix[rows[0]][cols[0]];
                for(int k = 0; k < 4; k++){//每次交换4个元素
                    if(k < 3) matrix[rows[k]][cols[k]] = matrix[rows[k+1]][cols[k+1]];
                    else matrix[rows[k]][cols[k]] = tmp;
                }
            }
        }
    }
};
只有0和1的世界是简单的
原文地址:https://www.cnblogs.com/nullxjx/p/14874597.html