Skip to content

矩阵旋转

leetcode

js
var rotate = function (matrix) {
    // 水平互换
    let n = matrix.length;
    let half = Math.floor(matrix.length / 2);
    for (let i = 0; i < half; i++) {
        for (let j = 0; j < n; j++) {
            [matrix[i][j], matrix[n - 1 - i][j]] = [
                matrix[n - 1 - i][j],
                matrix[i][j],
            ];
        }
    }
    // 主对角线互换
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
    }
    return matrix;
};
var rotate = function (matrix) {
    // 水平互换
    let n = matrix.length;
    let half = Math.floor(matrix.length / 2);
    for (let i = 0; i < half; i++) {
        for (let j = 0; j < n; j++) {
            [matrix[i][j], matrix[n - 1 - i][j]] = [
                matrix[n - 1 - i][j],
                matrix[i][j],
            ];
        }
    }
    // 主对角线互换
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
    }
    return matrix;
};

༼ つ/̵͇̿̿/’̿’̿ ̿ ̿̿ ̿̿◕ _◕ ༽つ/̵͇̿̿/’̿’̿ ̿ ̿̿ ̿̿ ̿̿