# Leetcode 48 旋转图像(Rotate Image) 题解分析 | Nicksxs's Blog
题目介绍You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix direct

# Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%

# Leetcode 48 旋转图像(Rotate Image) 题解分析

发表于 2021-05-01 分类于 Java ， leetcode ， Rotate Image 阅读次数： 阅读次数： Disqus：

### 题目介绍

You are given an n x n 2D `matrix` representing an image, rotate the image by 90 degrees (clockwise).

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.
如图，这道题以前做过，其实一看有点蒙，好像规则很容易描述，但是代码很难写，因为要类似于贪吃蛇那样，后来想着应该会有一些特殊的技巧，比如翻转等

### 代码

直接上码

    public void rotate(int[][] matrix) {
            // 这里真的傻了，长宽应该是一致的，所以取一次就够了
            int lengthX = matrix[0].length;
            int lengthY = matrix.length;
            int temp;
            System.out.println(lengthY - (lengthY % 2) / 2);
            // 这里除错了，应该是减掉余数再除 2
    //        for (int i = 0; i < lengthY - (lengthY % 2) / 2; i++) {
            /**
             * 1 2 3             7 8 9
             * 4 5 6     =>      4 5 6     先沿着 4 5 6 上下交换
             * 7 8 9             1 2 3
             */
            for (int i = 0; i < (lengthY - (lengthY % 2)) / 2; i++) {
                for (int j = 0; j < lengthX; j++) {
                    temp = matrix[i][j];
                    matrix[i][j] = matrix[lengthY-i-1][j];
                    matrix[lengthY-i-1][j] = temp;
                }
            }

            /**
             * 7 8 9               7 4 1
             * 4 5 6     =>        8 5 2   这里再沿着 7 5 3 这条对角线交换
             * 1 2 3               9 6 3
             */
            for (int i = 0; i < lengthX; i++) {
                for (int j = 0; j <= i; j++) {
                    if (i == j) {
                        continue;
                    }
                    temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = temp;
                }
            }
        }

还没到可以直接归纳题目类型的水平，主要是几年前做过，可能有那么点模糊的记忆，当然应该也有直接转的方法

相关文章

- Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析
- Leetcode 3 Longest Substring Without Repeating Characters 题解分析
- Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析
- Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析
- Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析