解题思路
这道题目其实更像是找规律的,找到规律后,可以使用旋转一圈的方式来实现,如图:
代码
var rotate = function(matrix) {
let len = matrix.length;
for (let i = 0; i < len / 2; i++){
for (let j = i; j < len - i - 1; j++) {
let temp = matrix[i][j];
let m = len - j - 1;
let n = len - i - 1;
matrix[i][j] = matrix[m][i];
matrix[m][i] = matrix[n][m];
matrix[n][m] = matrix[j][n];
matrix[j][n] = temp;
}
}
return matrix;
};
const matrix = [[1,2,3],[4,5,6],[7,8,9]]
// matrix = [[1,2,3],[4,5,6],[7,8,9]]
// 输出:[[7,4,1],[8,5,2],[9,6,3]]
// matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
// 输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
console.log(rotate(matrix));