矩阵,可以看做是一个二维数组,如何实现一个MXN的矩阵旋转,如顺时针旋转90°,180°,270°。
3X4 矩阵 :
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
顺时针90°,为4X3矩阵:{{9, 5, 1}, {10, 6, 2}, {11, 7, 3}, {12, 8, 4}}
顺时针180°,为3X4矩阵:{{12, 11, 10, 9}, {8, 7, 6, 5}, {4, 3, 2,1}}
顺时针270°,为4X3矩阵:{{4, 8, 12}, {3, 7, 11}, {2, 6, 10}, {1, 5, 9}}
代码如下:
package com.yx.test.util;
public class MatrixUtil {
public enum Rotation {
/**
* 不旋转
*/
ROTATION_0,
/**
* 右转90度
*/
ROTATION_90,
/**
* 右转180度
*/
ROTATION_180,
/**
* 右转270度
*/
ROTATION_270
}
/**
* 点阵旋转
*
* @param ori 原始点阵
* @param rotation 旋转后点阵
* @return 旋转后的点阵
*/
private static int[][] rotation(int[][] ori, Rotation rotation) {
if (rotation == null || ori == null) {
return null;
}
int row = ori.length;
int col = ori[0].length;
int[][] ret = null;
switch (rotation) {
case ROTATION_0:
ret = ori;
break;
case ROTATION_90:
ret = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ret[j][row - 1 - i] = ori[i][j];
}
}
break;
case ROTATION_180:
ret = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ret[row - 1 - i][col - 1 - j] = ori[i][j];
}
}
break;
case ROTATION_270:
ret = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ret[col - 1 - j][i] = ori[i][j];
}
}
break;
default:
break;
}
return ret;
}
/**
* 打印矩阵
* @param matrix 待打印矩阵
*/
private static void printMatrix(int[][] matrix) {
if (matrix != null) {
int row = matrix.length;
int col = matrix[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
printMatrix(matrix);
int[][] matrix90 = rotation(matrix, Rotation.ROTATION_90);
printMatrix(matrix90);
int[][] rotationMatrix180 = rotation(matrix, Rotation.ROTATION_180);
printMatrix(rotationMatrix180);
int[][] rotationMatrix270 = rotation(matrix, Rotation.ROTATION_270);
printMatrix(rotationMatrix270);
}
}
转换的关系式可以通过坐标系转换的思想理解。