Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

旋转矩阵 #317

Open
Sunny-117 opened this issue Nov 8, 2022 · 3 comments
Open

旋转矩阵 #317

Sunny-117 opened this issue Nov 8, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

lxy-Jason commented Nov 9, 2022

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function(matrix) {
    const n = matrix.length;
    const matrix_new = new Array(n).fill(0).map(() => new Array(n).fill(0)); //新矩阵
    for(let i = 0; i < n; i++){
        for(let j = 0; j < n; j++){
            matrix_new[j][n - i - 1] = matrix[i][j];
            //重点在这里,对于矩阵中第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。
           //倒数第i列相当于正数n-i列,因为下标从0开始,所以这里还要-1,第j个位置其实就是第j行
        }
    }
    for(let i = 0; i < n; i++){
        for(let j = 0; j < n; j++){
            matrix[i][j] = matrix_new[i][j];
        }
    }
};

@Achetto
Copy link

Achetto commented Dec 3, 2022

情况一:顺时针转 90 度:先转置再左右镜像
情况二:顺时针转 180 度:先上下镜像,再左右镜像(先左右再上下也可)
情况三:顺时针转 270 度:先转置再上下镜像

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function(matrix) {
  const l = matrix.length - 1;
  // 转置
  for (let i = 0; i <= l; i++) {
    for (let j = 0; j <= i; j++) {
      [matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]];
    }
  }
  // 左右翻转
  for (let i = 0; i <= l; i++) {
    for (let j = 0; j <= Math.floor(l / 2); j++) {
      [matrix[i][j],matrix[i][l - j]] = [matrix[i][l - j],matrix[i][j]];
    }
  }
};

@HangHZhang
Copy link

function rotateMatrix(m: number[][]):void {
    let m_length: number = m[0].length;
    let temp: number;
    for (let i = 0; i < m_length; i++) {
        for (let j = 0; j < Math.floor(m_length>>1); j++) {
            temp = m[i][j];
            m[i][j] = m[i][m_length-1-j];
            m[i][m_length-1-j]=temp;
        }
    }
    for (let i = 0; i < m_length-1; i++) {
        for (let j = 0; j < m_length-i-1; j++) {
            temp = m[i][j];
            m[i][j] = m[m_length-1-j][m_length-1-i];
            m[m_length-1-j][m_length-1-i] = temp;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants