【LeetCode】解题48:Rotate Image

Problem 48: Rotate Image [Medium]

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.

Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

Example 2:

Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

来源:LeetCode

解题思路

将数组看作一个由N/2个正方形圈组成的套圈,每一次循环都将一个圈在原地顺时针旋转90°,能够保证不会重复旋转,并且不需要额外数组空间。
如下图所示:
在这里插入图片描述
一次旋转圈1:
在这里插入图片描述
第二次旋转圈2:
在这里插入图片描述
具体过程:

  • 循环N/2次,每次旋转的正方形的四个顶点为:
    t o p _ l e f t = [ s i d e , s i d e ] , top\_left = [side, side], top_left=[side,side]
    t o p _ r i g h t = [ s i d e , N − s i d e − 1 ] , top\_right = [side, N-side-1], top_right=[side,Nside1]
    b o t t o m _ r i g h t = [ N − s i d e − 1 , N − s i d e − 1 ] , bottom\_right = [N-side-1, N-side-1], bottom_right=[Nside1,Nside1]
    b o t t o m _ l e f t = [ N − s i d e − 1 , s i d e ] bottom\_left = [N-side-1, side] bottom_left=[Nside1,side]
  • 旋转正方形时需要调换 4 ∗ ( N − 2 ∗ s i d e − 1 ) 4*(N-2*side-1) 4(N2side1)个点的位置。每四个点为一组,内部进行旋转替换,循环该过程 ( N − 2 ∗ s i d e − 1 ) (N-2*side-1) (N2side1)次。
    分组如图所示:
    在这里插入图片描述

运行结果:
在这里插入图片描述

Solution (Java)

class Solution {
    public void rotate(int[][] matrix) {
        int N = matrix.length;
        if(N == 0 || N == 1) return;
        for(int i = 0; i < N / 2; i++){
            rotate_sides(matrix, i, N);
        }
    }
    private void rotate_sides(int[][] matrix, int side, int N){
        for(int i = side; i < N - side - 1; i++){
            int top = matrix[side][i];
            int right = matrix[i][N-side-1];
            int bottom = matrix[N-side-1][N-i-1];
            int left = matrix[N-i-1][side];
            matrix[i][N-side-1] = top;
            matrix[N-side-1][N-i-1] = right;
            matrix[N-i-1][side] = bottom;
            matrix[side][i] = left;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值