美文网首页
LeetCode 48 RotateImage

LeetCode 48 RotateImage

作者: phantom34 | 来源:发表于2019-06-12 13:41 被阅读0次

    题目

    48. Rotate Image

    题目描述

    给定一个 n × n 的二维矩阵表示一个图像。
    将图像顺时针旋转 90 度。

    样例

    示例 1:
    给定 matrix =
    [
    [1,2,3],
    [4,5,6],
    [7,8,9]
    ],
    原地旋转输入矩阵,使其变为:
    [
    [7,4,1],
    [8,5,2],
    [9,6,3]
    ]
    示例 2:
    给定 matrix =
    [
    [ 5, 1, 9,11],
    [ 2, 4, 8,10],
    [13, 3, 6, 7],
    [15,14,12,16]
    ],
    原地旋转输入矩阵,使其变为:
    [
    [15,13, 2, 5],
    [14, 3, 4, 1],
    [12, 6, 8, 9],
    [16, 7,10,11]
    ]

    思路

    复制一个新的矩阵 然后 通过matrix[i][j] = matrix2[matrix.length - 1 - j][i]
    给原矩阵转换

    代码

        public static void rotate(int[][] matrix) {
            int[][] matrix2 = new int[matrix.length][matrix.length];
            for (int i = 0; i < matrix.length; i++)
                matrix2[i] = matrix[i].clone();
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    matrix[i][j] = matrix2[matrix.length - 1 - j][i];
                   // System.out.print("  " + matrix[i][j]);
                }
                //System.out.println();
            }
        }
    }
    

    结果

    image.png

    相关文章

      网友评论

          本文标题:LeetCode 48 RotateImage

          本文链接:https://www.haomeiwen.com/subject/oxbkfctx.html