LeetCode OJ算法题(四十七):Rotate Image

来源:互联网 发布:潜在因子推荐算法 编辑:程序博客网 时间:2024/05/03 13:11

题目:

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?

解法:

顺时针旋转90度,观察可知是将所有的A[ i ][ j ]移动到A[ j ][ n-1-i ]的位置,但是考虑到要in-place,所有只能使用交换元素的方法。

可以首先将A[ i ][ j ]与A[ n-1-j ][ n-1-i ]交换位置,再把矩阵上下对调,即A[n-1-j][n-1-i]变换到A[j][n-1-i]上,这样只要保证不重复交换,就能保证矩阵正确旋转!

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


0 0