二维矩阵旋转90°

旋转矩阵
将一个二维的正方形矩阵原地旋转90°

二维矩阵旋转90°_第1张图片

package struct;

//旋转90°打印二维矩阵
public class RotateMatrix {

    public static void rotateMatrix(int[][] matrix){
        int topRow = 0;
        int topCol = 0;
        int lowRow = matrix.length - 1;
        int lowCol = matrix[0].length - 1;
        while(topRow < lowRow){
            rotateEdge(matrix,topRow++,topCol++,lowRow--,lowCol--);
        }
    }

	//对矩阵的每一圈的四条边进行旋转
    public static void rotateEdge(int[][] m,int topRow,int topCol,int lowRow,int lowCol){
    	//每一条边有times个数字进行交换
        int times = lowCol - topCol;
        int tmp = 0;
        /**
         * 上边框:m[topRow][topCol + i]
         * 右边框:m[topRow + i][lowCol]
         * 下边框:m[lowRow][lowCol - i]
         * 左边框:m[lowRow - i][topCol]
         */
        for(int i = 0;i != times;i++){
            tmp = m[topRow][topCol + i];
            m[topRow][topCol + i] = m[lowRow - i][topCol];
            m[lowRow - i][topCol] = m[lowRow][lowCol - i];
            m[lowRow][lowCol - i] = m[topRow + i][lowCol];
            m[topRow + i][lowCol] = tmp;
        }
    }

    public static void main(String[] args){
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        rotateMatrix(matrix);
        for(int i = 0;i != matrix.length;i++){
            for(int j = 0;j != matrix[0].length;j++){
                System.out.print(" " + matrix[i][j]);
            }
            System.out.println();
        }
    }

}

你可能感兴趣的:(二维矩阵旋转90°)