2014年11月28日星期五

[Leetcode] 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?

Two method to do so. One is to swap according to the diagonal and then swap according to the middle row.

    public void rotate(int[][] matrix) {
        int m = matrix.length;
        if(m == 0)
            return; // corner case
        int n = matrix[0].length;
        // swap according to the diag
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n - i - 1; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n-1-j][m-1-i];
                matrix[n-1-j][m-1-i] = temp;
            }
        }
        // swap accoding to the middle
        int half = m / 2;
        for(int i = 0; i < half; i++) {
            for(int j = 0; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[m-i-1][j];
                matrix[m-i-1][j] = temp;
            }
        }
    }

Another way is to define four subarea and then swap them. If n is even then the subarea would be a square and if n is odd the subarea would be a rectangle with length and width differ by one.

    public void rotate(int[][] matrix) {
        int m = matrix.length;
        if(m == 0)
            return; // corner case
        int n = matrix[0].length;
        int x = m / 2;
        int y = (m+1) / 2; // subarea to be rotate
        for(int i = 0; i < x; i++) {
            for(int j = 0; j < y; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[m-1-j][i];
                matrix[m-1-j][i] = matrix[n-1-i][m-1-j];
                matrix[n-1-i][m-1-j] = matrix[j][n-1-i];
                matrix[j][n-1-i] = temp;
            }
        }
    }

没有评论:

发表评论