48. Rotate Image
Leetcode
題目
解答
var rotate = function(matrix) {
const n = matrix.length;
// 總共有幾圈
let round = Math.floor(n/2);
const swap = (x1, y1, x2, y2) => {
let temp = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = temp;
}
while(round>0) {
const start = Math.floor(n/2) - round;
const end = n-1-start;
// 標記左上、左下、右下位置
const initArr = [
{x1: start, y1: start, x2: end, y2: start},
{x1: end, y1: start, x2: end, y2: end},
{x1: end, y1: end, x2: start, y2: end}
]
for (let i=0; i<initArr.length; i++) {
let {x1, y1, x2, y2} = initArr[i];
for(let j=0; j<n-1-start*2; j++) {
swap(x1, y1, x2, y2);
if(i===0) {
x1++;
y2++;
}
if(i===1) {
y1++;
x2--;
}
if(i===2) {
x1--;
y2--;
}
}
}
round--;
}
};測資
Last updated
