【算法题】矩阵顺时针旋转90° (js)

力扣链接:https://leetcode.cn/problems/rotate-matrix-lcci/description/

【算法题】矩阵顺时针旋转90° (js)_第1张图片
本人题解:

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function (matrix) {
    const x = matrix.length || 0;
    const y = x > 0 ? matrix[0]?.length : 0;
    if (x === 0) return [];
    if (y === 1) return matrix;
    for (let i = 0; i < x; i++) {
        for (let j = i; j < y; j++) {
            const temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
    return matrix.map((item) => item.reverse());
};

你可能感兴趣的:(算法题,算法,矩阵,javascript)