Skip to content

Commit b807172

Browse files
committed
feat(soobing): week6 > spiral-matrix
1 parent bfdf3b2 commit b807172

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

spiral-matrix/soobing.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
*
3+
* 문제 설명
4+
* - 2차원 배열을 나선형으로 데이터 순회하여 1차원 배열로 담기
5+
* - 문제 풀이 타입의 알고리즘 문제 같음
6+
*
7+
* 아이디어
8+
* 1) 경계를 정하고 오른쪽, 아래, 왼쪽, 위로 순회한다.
9+
*
10+
*/
11+
function spiralOrder(matrix: number[][]): number[] {
12+
let left = 0;
13+
let top = 0;
14+
let right = matrix[0].length - 1;
15+
let bottom = matrix.length - 1;
16+
17+
const result: number[] = [];
18+
19+
while (left <= right && top <= bottom) {
20+
// 오른쪽
21+
for (let i = left; i <= right; i++) {
22+
result.push(matrix[top][i]);
23+
}
24+
top++;
25+
26+
// 아래
27+
for (let i = top; i <= bottom; i++) {
28+
result.push(matrix[i][right]);
29+
}
30+
right--;
31+
32+
// 왼쪽
33+
if (top <= bottom) {
34+
for (let i = right; i >= left; i--) {
35+
result.push(matrix[bottom][i]);
36+
}
37+
bottom--;
38+
}
39+
40+
// 위쪽
41+
if (left <= right) {
42+
for (let i = bottom; i >= top; i--) {
43+
result.push(matrix[i][left]);
44+
}
45+
left++;
46+
}
47+
}
48+
return result;
49+
}

0 commit comments

Comments
 (0)