首页 > 代码库 > Rotate Image

Rotate Image

题目

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

方法

矩阵坐标的转换,循环替换。
    public void rotate(int[][] matrix) {
        if(matrix != null && matrix.length != 0 && matrix.length != 1) {
            int len = matrix.length;
            int k = 0;
            int last = len - 1;
            while (k < len / 2) {
                for (int i = k; i < last - k; i++) {
                    int temp = matrix[k][i];
                    matrix[k][i] =matrix[last - i][k];
                    matrix[last - i][k] = matrix[last - k][last - i];
                    matrix[last - k][last - i] = matrix[i][last - k];
                    matrix[i][last - k] = temp;
                }
                k++;
            }
        }
    }