rotate-image

题目描述

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.

解决思路

这题的难点在就地置换上,采取先对角线交换元素再行顺序倒置元素的思路来解决问题
如图所示
沿对角线交换元素:
1 2 3 => 1 4 7
4 5 6 => 2 5 8
7 8 9 => 3 6 9
行顺序倒置元素:
1 4 7 => 7 4 1
2 5 8 => 8 5 2
3 6 9 => 9 6 3

代码

public void rotate(int[][] matrix) {
        int n = matrix[0].length;
        //按照对角线对换元素
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        //行顺序倒置
        for(int i=0;i<n;i++){
            for(int j=0;j<n/2;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][n-j-1];
                matrix[i][n-j-1] = temp;
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容