LeetCode周挑战-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 NOT allocate another 2D matrix and do the rotation.

描述:将一个N*N的数组顺时针翻转90度,并且不要使用额外的二位数组空间

LeetCode

分析:将原数组顺时针翻转90度,如果利用一个额外的N*N的数组,是非常好实现的,对应着将每一行赋值给另外一个数组的每一列就行了。

但是题目要求不能使用额外的数组,那就只能一个数字一个数字的替换。

LeetCode上讨论区有个人分享了一个做类似题目的思路;比如今天这道顺时针旋转90度,可以通过上下翻转,中心对称翻转实现。举一个例子来说,将一个水平的木棍放到跟一端垂直的方向,怎么做?我们可以以目标位置的中轴线为基准,对称平移原木棍,然后拉着原木棍的一端顺时针旋转90度即可。



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

    // 上下翻转

    int row = matrix.length;

    int col = matrix[0].length;

    for (int i =0,end=row/2; i < end; i++) {

        for (int j =0; j < col; j++) {

            int temp = matrix[i][j];

            matrix[i][j] = matrix[row-i-1][j];

            matrix[row-i-1][j] = temp;

        }

}

    // 对称翻转

    for (int i =0; i < row; i++) {

        for (int j = i+1; j < col; j++) {

            int temp = matrix[i][j];

            matrix[i][j] = matrix[j][i];

            matrix[j][i] = temp;

        }

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容