[leet code] Rotate Image

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?

Without followup, we can directly create a new n x n 2D matrix, then format the value of which as the rotation of the original matrix.

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] rotatedMatrix = new int[n][n];
        
        // Construct rotated matrix
        for (int i=0; i<n; i++){
            for (int j=0; j<n; j++){
                rotatedMatrix[j][n-1-i] = matrix[i][j];
            }
        }
        
        // Reformat override original matrix
        for (int i=0; i<n; i++){
            for (int j=0; j<n; j++){
                matrix[i][j] = rotatedMatrix[i][j];
            }
        }        
    }
}

In order to fulfill the follow up requirement,  i.e. in-place, we should utilize a temporary int variable and switch the values in the matrix.  Coming back to our problem, rotating a matrix can be divided into steps and each step responses to rotating specific layer of the matrix.  For example, when n=6 there are n/2 = 3 steps from outside layers to inside layers.

In each step, we can use an iteration to switch the values.

public 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++){ // i layers
            for(int j=i; j<n-i-1; j++){ // rotate for ith layer
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n-j-1][i];
                matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
                matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
                matrix[j][n-i-1] = temp;
            }
        }
        return;
    }
}

 A key point of this approach is the value range of variable j, it changes in each step according to the size of the layer.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值