给定一个整型正方形矩阵matrix,请把该矩阵调整成 顺时针旋转90度的样子。
【要求】 额外空间复杂度为O(1)。
Code
//coding=utf8
/*****************************************************
@Author: Alex
@Created Time : Tue 27 Aug 2019 09:21:41 AM CST
@File Name: main.java
@Blog: https://blog.csdn.net/weixin_43336281
****************************************************/
public class main{
public static void PrintMatrix(int [][] 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();
}
}
public static void Rotation(int [][] matrix, int leftRow, int leftColumn, int rightRow, int rightColumn) {
for (int i = 0; i < rightColumn - leftColumn; i++){
int temp = matrix[leftRow][leftColumn + i];
matrix[leftRow][leftColumn + i] = matrix[rightRow - i][leftColumn];
matrix[rightRow - i][leftColumn] = matrix[rightRow][rightColumn - i];
matrix[rightRow][rightColumn - i] = matrix[leftRow + i][rightColumn];
matrix[leftRow + i][rightColumn] = temp;
}
}
public static void RotationMatrix(int [][] matrix) {
int leftRow = 0, leftColumn = 0;
int rightRow = matrix.length - 1, rightColumn = matrix[0].length - 1;
while (leftRow < rightRow)
Rotation(matrix, leftRow++, leftColumn++, rightRow--, rightColumn--);
PrintMatrix(matrix);
}
public static void main(String[] args) {
int [][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
RotationMatrix(matrix);
}
}