給定一個整型正方形矩陣matrix,把該矩陣調整成 順時針旋轉90度
public class RotateMatrix {
public static void rotade(int[][] matrix) {
int rowLeft = 0;
int columnLeft = 0;
int rowRight = matrix.length - 1;
int columnRight = matrix[0].length - 1;
while (rowLeft < rowRight) {
rotageEdge(matrix, rowLeft++, columnLeft++, rowRight--, columnRight--);
}
}
private static void rotageEdge(int[][] matrix, int rowLeft, int columnLeft, int rowRight, int columnRight) {
int times = columnRight - columnLeft;// 總體交換的組數
for (int i = 0; i != times; i++) {
int tmp = matrix[rowLeft][columnLeft + i];
matrix[rowLeft][columnLeft + i] = matrix[rowRight - i][columnLeft];
matrix[rowRight - i][columnLeft] = matrix[rowRight][columnRight - i];
matrix[rowRight][columnRight - i] = matrix[rowLeft + i][columnRight];
matrix[rowLeft + i][columnRight] = tmp;
}
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
rotade(matrix);
printMatrix(matrix);
}
}