48. 旋转图像


给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。

你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。

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

class Solution {

    public void rotate(int[][] matrix) {

        if (matrix == null || matrix.length == 1) {
            return;
        }


        int row1 = 0, col1 = 0, row2 = matrix.length - 1, col2 = matrix.length - 1;

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

            row1++;
            col1++;
            row2--;
            col2--;
        }
    }
}

相关