leetcode:Rotate Image 【Java】

一、问题描述

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

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

二、问题分析

先沿着副对角线翻转一次;再沿着水平对称轴翻转一次。

三、算法代码

public class Solution {
    public void rotate(int[][] matrix) {
        int len = matrix.length;
        //沿副对角线旋转
        for(int i = 0; i <= len - 1; i++){
            for(int j = 0; j < len - i; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[len - 1 - j][len - 1 - i];
                matrix[len - 1 - j][len - 1 - i] = tmp;
            }
        }
        //沿水平中线翻转
        for(int i = 0; i < len / 2; i++){
            for(int j = 0; j <= len - 1; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[len - i - 1][j]; 
                matrix[len - i - 1][j] = tmp;
            }
        }
    }
}


你可能感兴趣的:(LeetCode)