Skip to content

Commit 7c5d157

Browse files
committed
add solution : 54. Spiral Matrix
1 parent 7d0ddc9 commit 7c5d157

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

spiral-matrix/mmyeon.ts

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* @link https://leetcode.com/problems/spiral-matrix/description/
3+
*
4+
* 접근 방법 :
5+
* - right -> bottom -> left -> top 순서로 진행하면서 경계 업데이트 처리
6+
*
7+
* 시간복잡도 : O(m x n)
8+
* - m x n 행렬의 모든 숫자 방문하니까 O(m x n)
9+
*
10+
* 공간복잡도 : O(n)
11+
* - 숫자 길이만큼 배열에 담음 *
12+
*/
13+
14+
function spiralOrder(matrix: number[][]): number[] {
15+
const result: number[] = [];
16+
// 경계 설정
17+
let top = 0,
18+
bottom = matrix.length - 1,
19+
left = 0,
20+
right = matrix[0].length - 1;
21+
22+
const moveRight = () => {
23+
for (let i = left; i <= right; i++) {
24+
result.push(matrix[top][i]);
25+
}
26+
top++;
27+
};
28+
29+
const moveDown = () => {
30+
for (let i = top; i <= bottom; i++) {
31+
result.push(matrix[i][right]);
32+
}
33+
right--;
34+
};
35+
36+
const moveLeft = () => {
37+
for (let i = right; i >= left; i--) {
38+
result.push(matrix[bottom][i]);
39+
}
40+
bottom--;
41+
};
42+
43+
const moveUp = () => {
44+
for (let i = bottom; i >= top; i--) {
45+
result.push(matrix[i][left]);
46+
}
47+
left++;
48+
};
49+
50+
while (top <= bottom && left <= right) {
51+
moveRight();
52+
moveDown();
53+
54+
if (top <= bottom) moveLeft();
55+
if (left <= right) moveUp();
56+
}
57+
58+
return result;
59+
}

0 commit comments

Comments
 (0)