思路:找规律
方法一、一般辅助数组解法
行列转换,第一行变到第三列,第二行变到第二列,第三行变到第一列
matrix[row][col] = matrix[col][n-row-1]
然后复制回原数组
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] matrix_new = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
matrix_new[j][n - i - 1] = matrix[i][j];
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
matrix[i][j] = matrix_new[i][j];
}
}
}
}
方法二、对角线翻转+左右翻转
矩阵性质,可以发现对角线翻转之后就是逆时针转了九十度,左右再翻转就是顺时针转了九十度
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int i = 0;i<n;i++){
//翻转一半
for(int j = i;j<n;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//翻转一半
for(int i = 0;i<n/2;i++){
for(int j = 0;j<n;j++){
int temp = matrix[j][i];
matrix[j][i] = matrix[j][n-i-1];
matrix[j][n-i-1] = temp;
}
}
}
}