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

《程序员面试金典(第 6 版)》01.07. 旋转矩阵 #103

Open
Tcdian opened this issue Apr 7, 2020 · 1 comment
Open

《程序员面试金典(第 6 版)》01.07. 旋转矩阵 #103

Tcdian opened this issue Apr 7, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 7, 2020

《程序员面试金典(第 6 版)》01.07. 旋转矩阵

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。

不占用额外内存空间能否做到?

Example 1

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2

给定 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]
]
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 7, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function(matrix) {
    const sideLen = matrix.length;
    const mid = Math.floor(sideLen / 2);
    for (let i = 0; i < mid; i++) {
        for (let j = 0; j < sideLen; j++) {
            swap(matrix, i, j, sideLen - 1 - i, j);
        }
    }
    for (let i = 1; i < sideLen; i++) {
        for(let j = 0; j < i; j++) {
            swap(matrix, i, j, j, i);
        }
    }
};

function swap(matrix, x1, y1, x2, y2) {
    const temp = matrix[x1][y1];
    matrix[x1][y1] = matrix[x2][y2];
    matrix[x2][y2] = temp;
}

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

No branches or pull requests

1 participant