Skip to content

Commit a16a983

Browse files
authored
[ PS ] : Rotate Image
1 parent 1022935 commit a16a983

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

rotate-image/uraflower.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {void} Do not return anything, modify matrix in-place instead.
4+
*/
5+
const rotate = function (matrix) {
6+
const n = matrix.length;
7+
8+
// 상하좌우 겉에서부터 한 겹씩 안으로 진입
9+
for (let layer = 0; layer < Math.floor(n / 2); layer++) {
10+
11+
// layer 위의 각 칸들을 rotate
12+
// 하나를 rotate했을 때 연쇄적으로 rotate되는 규칙을 이용해
13+
// 네 칸 rotate하는 걸 x번 반복함
14+
15+
// x = n - 2 * layer - 1
16+
// 전체 배열 크기 n에서 layer만큼 안쪽으로 들어가야 하는데
17+
// 상하, 좌우만큼 들어가야 하니까 2를 곱함
18+
// 1을 안 빼면 이미 rotate한 자리를 다시 rotate하므로 빼줌
19+
20+
for (let i = 0; i < n - 2 * layer - 1; i++) {
21+
const top = layer;
22+
const bottom = n - 1 - layer;
23+
const left = top;
24+
const right = bottom;
25+
26+
const topLeft = matrix[top][left + i];
27+
matrix[top][left + i] = matrix[bottom - i][left];
28+
matrix[bottom - i][left] = matrix[bottom][right - i];
29+
matrix[bottom][right - i] = matrix[top + i][right];
30+
matrix[top + i][right] = topLeft;
31+
}
32+
}
33+
};
34+
35+
// 시간복잡도: O(n^2)
36+
// 공간복잡도: O(1)
37+
38+
// 참고로 중첩 구조를 다음과 같이 바꿔도 됨
39+
const top = 0;
40+
const bottom = n - 1;
41+
42+
while (top < bototm) {
43+
const left = top;
44+
const right = bottom;
45+
46+
for (let i = top; i < bottom; i ++) {
47+
// rotate
48+
}
49+
50+
top++;
51+
bottom--;
52+
}

0 commit comments

Comments
 (0)