48. 旋转图像 Rotate Image

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOTallocate another 2D matrix and do the rotation.

 

方法:

旋转90度时记得时i和j互换

 

public void rotate(int[][] matrix) {
        int row = matrix.length / 2;
        int col = matrix[0].length / 2;
        if(matrix[0].length % 2 == 1) col +=1;
        for(int i = 0; i < row; i++){
            for (int j = 0; j < col; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[matrix.length-1-j][i];
                matrix[matrix.length-1-j][i] = matrix[matrix.length-1-i][matrix[0].length-1-j];
                matrix[matrix.length-1-i][matrix[0].length-1-j] = matrix[j][matrix[0].length-1-i];
                matrix[j][matrix[0].length-1-i] = tmp;
            }
        }
    }

 

参考链接:

https://leetcode.com/problems/rotate-image/

https://leetcode-cn.com/problems/rotate-image/

posted @ 2020-12-23 13:38  diameter  阅读(105)  评论(0编辑  收藏  举报