LeetCode:Rotate Image - 将矩阵顺时针旋转90°

一、题目名称java

Rotate Image(将矩阵顺时针旋转90°)code

二、题目地址图片

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

三、题目内容get

英文:io

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

Rotate the image by 90 degrees (clockwise).方法

中文:im

现有一张图片保存在n×n大小的二维矩阵中。将它延顺时针方向旋转90度。英文

四、解题方法1

第一种方法,是先将原矩阵复制到另外一个矩阵中,再从另外一个矩阵的对应位置将值赋到原矩阵中矩阵旋转90°后的位置上。

Java代码以下:

/**
 * 顺时针旋转矩阵
 * @文件名称 Solution.java
 * @文件做者 Tsybius2014
 * @建立时间 2016年4月15日 下午3:55:55
 */
public class Solution {
    /**
     * 顺时针旋转矩阵
     * @param matrix 矩阵
     */
    public void rotate(int[][] matrix) {
        //空矩阵不处理
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        //矩阵的高和宽
        int height = matrix.length;
        int width = matrix[0].length;
        //高与宽必须一致
        if (height != width) {
            return;
        }
        //矩阵边长
        int len = height;
        //旋转矩阵
        //System.out.println("开始旋转");
        //复制一个新矩阵
        int[][] matrixTmp = new int[len][len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                matrixTmp[i][j] = matrix[i][j];
            }
        }
        //根据新矩阵计算老矩阵每一个元素旋转后的值
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                matrix[i][j] = matrixTmp[len - j - 1][i];
            }
        }
        //System.out.println("旋转完毕");
    }
}

五、解题方法2

第二种方法无须创建一个新矩阵,一次能够旋转4个点。

下图以5×5矩阵为例,红色的圈表明考虑要旋转一轮的点,绿色以点(0, 1)为例,说明每轮旋转的方向。

实现此方法的Java代码以下:

/**
 * 顺时针旋转矩阵
 * @文件名称 Solution.java
 * @文件做者 Tsybius2014
 * @建立时间 2016年4月15日 下午3:55:55
 */
public class Solution {
    /**
     * 顺时针旋转矩阵
     * @param matrix 矩阵
     */
    public void rotate(int[][] matrix) {
        //空矩阵不处理
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        //矩阵的高和宽
        int height = matrix.length;
        int width = matrix[0].length;
        //高与宽必须一致
        if (height != width) {
            return;
        }
        //矩阵边长
        int len = height;
        //旋转矩阵
        //System.out.println("开始旋转");
        int temp = 0;
        for (int i = 0; i < len / 2; i++) {
            for (int j = i; j < len - i - 1; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[len - j - 1][i];
                matrix[len - j - 1][i] = matrix[len - i - 1][len - j - 1];
                matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1];
                matrix[j][len - i - 1] = temp;
            }
        }
        //System.out.println("旋转完毕");
    }
}

END

相关文章
相关标签/搜索