方法一
⼀圈⼀圈的循环交换
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n/2; i++){
for(int j =i; j < n-i-1; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = temp;
}
}
}
}
方法二
以先转置,然后把每列对称交换交换⼀下。
class Solution {
public void rotate(int[][] matrix) {
//以对⻆线为轴交换
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j <=i; j++) {
if (i == j) {
continue;
}
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//交换列
for (int i = 0, j = matrix.length - 1; i < matrix.length / 2; i++, j--) {
for (int k = 0; k < matrix.length; k++) {
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j] = temp;
}
}
}
}