旋转关系: mat[j][n-i-1] = mat[i][j];

开辟新空间:

class Solution {
public:
    vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) {
        // write code here
        vector<vector<int> > ans(n, vector<int>(n,0));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                ans[j][n-i-1] = mat[i][j];
            }
        }
        return ans;
    }
};

原地:

class Solution {
public:
    vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) {
        //上下对称交换
        for(int i = 0; i < n/2; i++){
            for(int j = 0; j < n; j++){
                swap(mat[i][j], mat[n-i-1][j]);
            }
        }
        //主对角线交换
        for(int i = 0; i < n; i++){
            for(int j = i+1; j < n; j++){
                swap(mat[i][j], mat[j][i]);
            }
        }
        return mat;
    }
};