CTCI 1.6

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

Each time rotate 4 pixles (i, j), (j, n-i), (n-i, n-j) and (n-j, i). We iterate i and j in a upper-left quater square. However, when N is odd, the four quater square would have overlap, so some modification should be made, and the square changes to a rectangle.

/*Implemention problem, we first need to know the scale of N, we assume int is Ok to restore it, then according
to the problem, each pixel is 4 bytes, then int is enough, we also assume that we rotate the matrix anticlockwise.
It is easy to show that the four corresponding position in the matrix is (i, j), (j, n-i), (n-i, n-j) and (n-j, i).
We just need to iterate the upper-left quater of the matrix, but be careful with odd N, there exist overlap during
the rotation if we apply the same method like even N 
*/

public class RotateMatrix {
    public void rotateMatrix(int[][] matrix) {
        int n = matrix.length; if(n == 0) return ;
        int p = 0, q = 0;
        if(n%2 == 0) { p = n/2; q = n/2;}
        else {p = (n+1)/2; q = n/2;}

        for(int i = 0; i < p; i++) {
            for(int j = 0; j < q; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][n-i-1];
                matrix[j][n-i-1] = matrix[n-i-1][n-j-1];
                matrix[n-i-1][n-j-1] = matrix[n-j-1][i];
                matrix[n-j-1][i] = temp;
            }
        }
    }

    public void print(int[][] matrix) {
        int n = matrix.length; 
        if(n == 0) return;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println("");
        }
    }

    public static void main(String[] args) {
        RotateMatrix rm = new RotateMatrix();
        int[][] matrix1 = {{1}};
        int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix3 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        int[][] matrix4 = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};
        rm.rotateMatrix(matrix1);
        rm.print(matrix1);
        rm.rotateMatrix(matrix2);
        rm.print(matrix2);
        rm.rotateMatrix(matrix3);
        rm.print(matrix3);
        rm.rotateMatrix(matrix4);
        rm.print(matrix4);

    }
}

 

转载于:https://www.cnblogs.com/pyemma/p/3828417.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值