48. Rotate Image
2016-09-22 本文已影响38人
exialym
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
标准方法,先把矩阵上下颠倒,然后再根据左上至右下的对角线对称反转:
1 2 3 => 7 8 9 => 7 4 1
4 5 6 => 4 5 6 => 8 5 2
7 8 9 => 1 2 3 => 9 6 3
var rotate = function(matrix) {
matrix.reverse();
for (var i = 0; i < matrix.length; ++i) {
for (var j = 0; j < i; ++j) {
var temp = matrix[j][i];
matrix[j][i] = matrix[i][j];
matrix[i][j] = temp;
}
}
};
我想到了一个新的,哈哈哈,谁能看懂~
var rotate = function(matrix) {
var n = matrix.length;
var buff_len = n-1;
var count = 0;
while (buff_len>0) {
var a = count;
var b = count+buff_len;
for (var i = 0;i < buff_len;i++) {
var temp1 = matrix[a+i][b];
matrix[a+i][b] = matrix[a][a+i];
var temp2 = matrix[b][b-i];
matrix[b][b-i] = temp1;
var temp3 = matrix[b-i][a];
matrix[b-i][a] = temp2;
matrix[a][a+i] = temp3;
}
count++;
buff_len-=2;
}
};
就是从最外圈开始,一圈一圈的换。