-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathrotateImage.js
51 lines (42 loc) · 1.06 KB
/
rotateImage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// TC: O(n^2) SC: O(1)
function rotateImage(matrix) {
let left = 0, right = matrix[0].length-1;
while(left < right) {
for(let i=0; i< right - left; i++) {
let top = left, bottom = right;
// Save the topLeft
let topLeft = matrix[top][left+i];
//Move bottom left to top left
matrix[top][left+i] = matrix[bottom-i][left];
//Move bottom right to bottom left
matrix[bottom-i][left] = matrix[bottom][right-i];
//Move top right to bottom right
matrix[bottom][right-i] = matrix[top+i][right];
//Move top left to top right
matrix[top+i][right] = topLeft;
}
left++;
right--;
}
}
let matrix1 = [
[1, 2],
[3, 4]
];
let matrix2 = [
[1,2,3],
[4,5,6],
[7,8,9]
];
let matrix3 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
rotateImage(matrix1);
rotateImage(matrix2);
rotateImage(matrix3);
console.log(matrix1);
console.log(matrix2);
console.log(matrix3);