Rotate Image

来源:互联网 发布:9090端口 编辑:程序博客网 时间:2024/06/08 09:10

原题:

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

Rotate the image by 90 degrees (clockwise).

Note:
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.

Example 1:

Given input matrix = [  [1,2,3],  [4,5,6],  [7,8,9]],rotate the input matrix in-place such that it becomes:[  [7,4,1],  [8,5,2],  [9,6,3]]

即给一个矩阵代表图片所有像素点,将矩阵所有元素顺时针转九十度,实现将图片旋转九十度。只允许在原矩阵操作,不能用新的矩阵。


思考过程&解题思路:

关键在于元素新位置和原位置关系。发现matrix[i][j]新位置是matrix[j][n - 1 - i]。但是只能在原矩阵上操作,不能简单的赋值或者交换值。每次旋转都是四个点为一组,他们四个互相咬尾巴交换位置(我想之所以是四个元素,不是三个,五个,是因为90度乘4等于360度)。这就要求每组只换一次,所以要标记这一组换没换。


结果代码:

public void rotate(int[][] matrix) {        if (matrix.length == 0) return;;        int n = matrix[0].length;        boolean[][] isRotated = new boolean[n][n];//java boollean初始化默认为false,用于标记该组元素是否换过位置,避免重复换        for (int i = 0;i < n;i++)            for (int j = 0;j < n;j++){            rotateFourElements(matrix,isRotated,i,j);            }    }    public void rotateFourElements(int[][] matrix,boolean[][] isRotated,int i,int j){//四个元素交换位置        if (!isRotated[i][j]){            int x = matrix[i][j],n = matrix[0].length;            matrix[i][j] = matrix[n - 1 - j][i];            matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 -j];            matrix[n - 1 - i][n - 1 -j] = matrix[j][n - 1 - i];            matrix[j][n - 1 - i] = x;            isRotated[i][j] = true;            isRotated[j][n - 1 - i] = true;            isRotated[n - 1 - i][n - 1 -j] = true;            isRotated[n - 1 - j][i] = true;        }    }