Rotate Image

https://leetcode.com/problems/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?

解题思路:

先写一个不是in-place的。多写几个例子,就能看出来旋转后的矩阵和原矩阵下标的关系就是:result[j][matrix.length - 1 - i] = matrix[i][j]。

还要注意最后如果写matrix = result是不能把matrix赋值的,因为java是pass by value。

public class Solution {

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

        int[][] result = new int[matrix.length][matrix.length];

        for(int i = 0; i < matrix.length; i++){

            for(int j = 0; j < matrix.length; j++){

                result[j][matrix.length - 1 - i] = matrix[i][j];

            }

        }

        for(int i = 0; i < matrix.length; i++){

            for(int j = 0; j < matrix.length; j++){

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

            }

        }

    }

}

 下面考虑in place的方法。我是没看出来,参考了其他网友的方法。

http://fisherlei.blogspot.jp/2013/01/leetcode-rotate-image.html

思路就是,第一步,按照从左下到右上的对角线做对称,第二部,按照横向中线做对称即可。

public class Solution {

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

        //先按从左下到右上的对角线做对称

        for(int i = 0; i < matrix.length; i++){

            for(int j = 0; j < matrix.length - i; j++){

                int temp = matrix[matrix.length - 1 - j][matrix.length - 1 - i];

                matrix[matrix.length - 1 - j][matrix.length - 1 - i] = matrix[i][j];

                matrix[i][j] = temp;

            }

        }

        

        //再按照横向的中心对称

        int start = 0;

        int end = matrix.length - 1;

        while(start < end){

            for(int i = 0; i < matrix.length; i++){

                int temp = matrix[start][i];

                matrix[start][i] = matrix[end][i];

                matrix[end][i] = temp;

            }

            start++;

            end--;

        }

    }

}

如果做逆时针变换,则是第一步,按照左上右下的对角线做对称,第二部还是按照横向中线做对称。

总结一下,这道题如果不in place,只要找出对应的index变换方程就行了,但是这里的方程不是swap,而是循环赋值。要求in place,就一定要找出swap的方法。没做出来,需要记住。

update 2015/05/22

二刷,先按照从左上到右下的对角线对折,再按照竖着的中线对折,也可以。

public class Solution {

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

        int n = matrix.length;

        if(n == 0) {

            return;

        }

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

            for(int j = i; j < n; j++) {

                int temp = matrix[i][j];

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

                matrix[j][i] = temp;

            }

        }

        int start = 0;

        int end = matrix.length - 1;

        while(start < end){

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

                int temp = matrix[i][start];

                matrix[i][start] = matrix[i][end];

                matrix[i][end] = temp;

            }

            start++;

            end--;

        }

    }

}

 

你可能感兴趣的:(image)