【leetcode】48. 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.

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] ]

解法

辣鸡韩梅梅,做了好久,这本该很快做出来的,思路就是把整个正方形分成一圈一圈的框,将框中每一个值旋转90操作,细节还是有点的。。总是对index不是很敏感,需要通过debug来调对。这次没看别人的解法还挺棒的,再接再厉!

class Solution {
    int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
    public void rotate(int[][] matrix) {
        for(int i=0; i<matrix.length/2; i++){
            matrix = rotate_one_square(matrix, i, matrix.length-i-1);
        }

    }
    
    private int[][] rotate_one_square(int[][] matrix, int begin, int end){
        System.out.println("beg "+begin+" "+end);
        int len = end - begin + 1;
        int next_column, next_row, cur_row, cur_column, cur_value;
        int[] arr = new int[len-1];

        cur_row = begin;
        cur_column = begin;
        for(int i = 0; i < len-1; i++){
            arr[i] = matrix[cur_row][cur_column+i];
        }
        
        System.out.println("cur "+cur_row+" "+cur_column);
        for(int j = 0; j < 4; j++){
            next_row = cur_row + dir[j][0]*(len-1);
            next_column = cur_column + dir[j][1]*(len-1);
            System.out.println("before next "+next_row+" "+next_column);
            if (next_row >= begin+len){
                next_column += next_row - begin - len + 1;
                next_row = begin + len - 1;
            }
            if (next_column >= begin+len){
                next_row += next_column - begin - len + 1;
                next_column =  begin + len - 1;
            }
            System.out.println("next "+next_row+" "+next_column);
            
            
       for(int i = 0; i < len-1; i++){
           System.out.println("replace "+(next_row+i*dir[(j+1)%4][0])+" "+(next_column+i*dir[(j+1)%4][1])+" with "+ arr[i]);
           int temp = matrix[next_row+i*dir[(j+1)%4][0]][next_column+i*dir[(j+1)%4][1]];
           matrix[next_row+i*dir[(j+1)%4][0]][next_column+i*dir[(j+1)%4][1]] = arr[i];
           arr[i] = temp;
           
        }
            
            cur_row = next_row;
            cur_column = next_column;
        }
    
        return matrix;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值