[LeetCode]Rotate Image(矩阵旋转)

48. Rotate Image

 
 
Total Accepted: 69437 Total Submissions: 198781 Difficulty: Medium

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

 

显然的,矩阵旋转。

 

这里我是多开一个数组来直接赋值,没有原地翻转。

或许原地翻转能更快。

 

package leetcode.RotateImage;

public class Solution {

    public void rotate( int[][] matrix ) {
        int[][] newMatrix = new int[ matrix.length ][ matrix[ 0 ].length ];
        int sX = 0;
        int sY = 0;
        int eX = matrix.length - 1;
        int eY = matrix[ 0 ].length - 1;
        while( sX <= eX && sY <= eY ) {
            int sx = sX;
            int sy = sY;
            int ex = eX;
            int ey = eY;
            roteUpToRight( matrix, newMatrix, sx, sy, ey );
            roteRightToBottom( matrix, newMatrix, sx, sy, ex, ey );
            roteBottomToLeft( matrix, newMatrix, sx, sy, ex, ey );
            roteLeftToUp( matrix, newMatrix, sx, sy, ex, ey );
            sX++;
            sY++;
            eX--;
            eY--;
        }
        for( int i = 0; i < matrix.length; i++ ) {
            for( int j = 0; j < matrix[ 0 ].length; j++ ) {
                matrix[ i ][ j ] = newMatrix[ i ][ j ];
            }
        }
    }

    private void roteLeftToUp( int[][] matrix, int[][] newMatrix, int sx, int sy, int ex, int ey ) {
        for( int i = sy,r=0; i < ey; i++,r++ ) {
            newMatrix[ sx ][ i ] = matrix[ ex - r ][ sx ];
        }
    }

    private void roteBottomToLeft( int[][] matrix, int[][] newMatrix, int sx, int sy, int ex, int ey ) {
        for( int i = sx; i < ex; i++ ) {
            newMatrix[ i ][ sy ] = matrix[ ex ][ i ];
        }
    }

    private void roteRightToBottom( int[][] matrix, int[][] newMatrix, int sx, int sy, int ex, int ey ) {
        for( int i = sy,r=0; i <= ey; i++,r++ ) {
            newMatrix[ ex ][ i ] = matrix[ ey-r  ][ ey ];
        }
    }

    private void roteUpToRight( int[][] matrix, int[][] newMatrix, int sx, int sy, int ey ) {
        for( int i = sy; i <= ey; i++ ) {
            newMatrix[ i ][ ey ] = matrix[ sx ][ i ];
        }
    }

    public static void main( String[] args ) {
        //int[][] matrix = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
        // int[][] matrix = new int[][]{{6,7},{9,10}};
         int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        Solution s = new Solution();
        s.rotate( matrix );
    }

}

 

posted @ 2016-05-31 10:39  hudiwei-hdw  阅读(202)  评论(0编辑  收藏  举报