8000 Merge pull request #4 from ignacio-chiazzo/rotate-image · SivaCse/leetcode-javascript@6d34381 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6d34381

Browse files
Merge pull request chihungyu1116#4 from ignacio-chiazzo/rotate-image
clearer solution rotate image
2 parents f2425f7 + f0235cc commit 6d34381

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

48 Rotate Image.js

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,20 @@
1111
*/
1212
var rotate = function(matrix) {
1313
var row = matrix.length;
14-
14+
1515
if(row === 0) {
1616
return;
1717
}
18-
18+
1919
var col = matrix[0].length;
20-
20+
2121
// swap them in diagonal
2222
for(var i = 0; i < row; i++) {
2323
for(var j = 0; j < col - i; j++) {
2424
swap(matrix, i, j, row - 1 - j, col - 1 - i);
2525
}
2626
}
27-
27+
2828
// swap in middle
2929
for(i = 0; i < Math.floor(row/2); i++) {
3030
for(j = 0; j < col; j++) {
@@ -37,4 +37,37 @@ function swap(matrix, x1, y1, x2, y2) {
3737
var tmp = matrix[x1][y1];
3838
matrix[x1][y1] = matrix[x2][y2];
3939
matrix[x2][y2] = tmp;
40-
}
40+
}
41+
42+
//Clearer Solution
43+
var rotate = function(matrix) {
44+
rotateColumns(matrix);
45+
rotateEachDiagonal(matrix);
46+
};
47+
48+
var rotateColumns = function(matrix) {
49+
for(var j = 0; j < matrix.length; j++) {
50+
var low = 0;
51+
var ceil = matrix.length -1;
52+
while(low < ceil) {
53+
swap(matrix, low, j, ceil, j);
54+
low++;
55+
ceil--;
56+
}
57+
}
58+
};
59+
60+
var rotateEachDiagonal = function(matrix){
61+
for(var i = 0; i < matrix.length; i++) {
62+
for(var j = i; j < matrix.length; j++) {
63+
swap(matrix, i, j, j, i);
64+
}
65+
}
66+
};
67+
68+
var swap = function(matrix, i1, j1, i2, j2) {
69+
var aux = matrix[i1][j1];
70+
matrix[i1][j1] = matrix[i2][j2];
71+
matrix[i2][j2] = aux;
72+
};
73+

0 commit comments

Comments
 (0)
0