# 二维数组的花式遍历
按照左上到右下的对角线进行镜像对称
按照右上到左下的对角线进行镜像对称
翻转一位数组
按照左上到右下的对角线进行镜像对称 + 翻转一位数组 = 顺时针旋转 90 度
按照右上到左下的对角线进行镜像对称 + 翻转一位数组 = 逆时针旋转 90 度
# 按照左上到右下的对角线进行镜像对称
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
// 先沿对角线镜像对称二维矩阵
const n = matrix.length
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
;[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]
}
}
# 翻转一位数组
const a = [1, 2, 3, 4, 5, 6]
function reverse(arr) {
let l = 0
let r = arr.length - 1
while (l < r) {
;[arr[l], arr[r]] = [arr[r], arr[l]]
l++
r--
}
}
reverse(a)
# 按照右上到左 i 下的对角线进行镜像对称
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
// 先沿对角线镜像对称二维矩阵
const n = matrix.length
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i; j++) {
;[matrix[i][j], matrix[n - j - 1][n - i - 1]] = [matrix[n - j - 1][n - i - 1], matrix[i][j]]
}
}
# 48. 旋转图像 (opens new window)
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function (matrix) {
const n = matrix.length
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
;[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]
}
}
function reverse(arr) {
let l = 0
let r = arr.length - 1
while (l < r) {
;[arr[l], arr[r]] = [arr[r], arr[l]]
l++
r--
}
}
for (let i = 0; i < n; i++) {
reverse(matrix[i])
}
}