LeetCode 面试题 01.07. 旋转矩阵

面试题 01.07. 旋转矩阵

题目:

LeetCode 面试题 01.07. 旋转矩阵_第1张图片


题解: M[i][j] = M[N - j][i]

官方题解:

https://leetcode-cn.com/problems/rotate-matrix-lcci/solution/xuan-zhuan-ju-zhen-by-leetcode-solution/


代码:

// M[i][j] = M[n-1-j][i]
// 1 M[i][j] = M[n - 1 - i][j]
// 2 M[i][j] = M[j][i]
// 由1 2可以推导出M[i][j] = M[n-1-j][i]

class Solution {
public:
    void rotate(vector>& matrix) {
        if (matrix.empty() || matrix.size() != matrix[0].size()) {
            return;
        }
        size_t n = matrix.size();
        int temp = 0;
        // 上下翻转
        for (int i = 0; i < n / 2; i++) {
            for (int j = 0; j < n; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 -i][j];
                matrix[n - 1 -i][j] = temp;
            }
        }

        // 对角线翻转
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }

        }
    }
};
// M[i][j] = M[n-1-j][i]
// 1 M[i][j] = M[i][n - 1 - j]
// 2 M[i][j] = M[n - 1 - j][n - 1 - i]
// 由1 2可以推导出M[i][j] = M[n-1-j][i]
class Solution_2 {
public:
    void rotate(vector>& matrix) {
        if (matrix.empty() || matrix.size() != matrix[0].size()) {
            return;
        }
        size_t n = matrix.size();
        int temp = 0;
        // 左右翻转
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n / 2; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[i][n - 1 -j];
                matrix[i][n - 1 -j] = temp;
            }
        }

        // 对角线翻转
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - i; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                matrix[n - 1 - j][n - 1 - i] = temp;
            }
        }
    }
};

 

你可能感兴趣的:(leetcode,matrix,算法)