面试题 01.07. 旋转矩阵(Interview question 01.07 Rotation matrix)

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。

不占用额外内存空间能否做到?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-matrix-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public void rotate(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;

        int row1 = 0, col1 = 0, row2 = m - 1, col2 = n - 1;

        while (row1 < row2 && col1 < col2) {
            for (int i = col1; i < col2; ++i) {
                int t = matrix[row1][i];
                matrix[row1][i] = matrix[row2 - (i - col1)][col1];
                matrix[row2 - (i - col1)][col1] = matrix[row2][col2 - (i - col1)];
                matrix[row2][col2 - (i - col1)] = matrix[row1 + (i - col1)][col2];
                matrix[row1 + (i - col1)][col2] = t;
            }
            row1++;
            col1++;
            row2--;
            col2--;
        }
        
    }
}
————————

Here’s a picture by n × N matrix represents the image, where the size of each pixel is 4 bytes. Please design an algorithm to rotate the image 90 degrees.

Can you do it without taking up additional memory space?

Source: leetcode
Link: https://leetcode-cn.com/problems/rotate-matrix-lcci
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

class Solution {
    public void rotate(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;

        int row1 = 0, col1 = 0, row2 = m - 1, col2 = n - 1;

        while (row1 < row2 && col1 < col2) {
            for (int i = col1; i < col2; ++i) {
                int t = matrix[row1][i];
                matrix[row1][i] = matrix[row2 - (i - col1)][col1];
                matrix[row2 - (i - col1)][col1] = matrix[row2][col2 - (i - col1)];
                matrix[row2][col2 - (i - col1)] = matrix[row1 + (i - col1)][col2];
                matrix[row1 + (i - col1)][col2] = t;
            }
            row1++;
            col1++;
            row2--;
            col2--;
        }
        
    }
}