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

你可能感兴趣的:(rotate-image)