觀前提醒:
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:
Input: matrix = [[1]]
Output: [[1]]
Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Constraints:
這題我卡了一陣子,後來我是去 google 下關鍵字 "Matrix rotation by 90 degrees",跑出這篇文章。
照著文章中提到的:
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function (matrix) {
const n = matrix.length;
// i 代表 row,j 代表 column。
// 先把二維陣列中, matrix[i][j] & matrix[j][i] 的數值對調。(transpose: 轉置矩陣)
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// 再把每一個row,直接做 reverse。即可得
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
};
這題一開始,看到關鍵字"Rotate" + "matrix"
,我還想興沖沖跑去書櫃旁,找到那塵封已久的線性代數筆記,打開"旋轉矩陣"的章節,想說好好的來研究研究一番XDDDD
p.s 周老師的網站真D好用,寫文章到一半,發現某些觀念忘了,還可以趕快找來複習一波哈哈哈
但是,我發現一般刷題時,通常不會需要調用到這麼多的數學函式啊,這樣整個效率會很低落耶,我們又不是要考研究所當榜首沒事拿石頭砸自己腳幹嘛XD