Skip to content

Commit dd72377

Browse files
committed
add: solve DaleStudy#282 Spiral Matrix with ts
1 parent df48a41 commit dd72377

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

โ€Žspiral-matrix/Yjason-K.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 2์ฐจ์› ๋ฐฐ์—ด์„ [0][0] ์‹œ์ž‘์œผ๋กœ ์‹œ๊ณ„๋ฐฉํ–ฅ์œผ๋กœ 1์ฐจ์› ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜.
3+
*
4+
* @param {number[][]} matrix - 2์ฐจ์› ๋ฐฐ์—ด
5+
* @returns {number[]} ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ 1์ฐจ์›์œผ๋กœ ํŽผ์นœ ๋ฐฐ์—ด
6+
*
7+
*
8+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n * m)
9+
* ๋ชจ๋“  ์›์†Œ๊ฐ€ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ๋˜๋ฏ€๋กœ ํ–‰๊ณผ ์—ด์˜ ๊ณฑ์— ๋น„๋ก€ํ•ฉ๋‹ˆ๋‹ค.
10+
*
11+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n * m)
12+
* ๋ฐฉ๋ฌธ ๋ฐฐ์—ด๊ณผ ์ถœ๋ ฅ ๋ชฉ๋ก์ด ํ•„์š”ํ•˜๋ฉฐ, ๋‘˜ ๋‹ค ์ž…๋ ฅ ๋ฐฐ์—ด์˜ ํฌ๊ธฐ์™€ ๊ฐ™์€ ์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
13+
*/
14+
function spiralOrder(matrix: number[][]): number[] {
15+
// ๋ฐฉ๋ถ„ ๋ฐฐ์—ด ์ƒ์„ฑ
16+
const visited: boolean[][] = Array.from({length: matrix.length}, () => Array(matrix[0].length).fill(false));
17+
// flattenํ•  ๋ฐฐ์—ด
18+
const orderList: number[] = [];
19+
// ์ „์ฒด ๊ธธ์ด
20+
const totalLength = matrix.length * matrix[0].length;
21+
// ์ง„ํ–‰ ๋ฐฉํ–ฅ (์šฐ, ํ•˜, ์ขŒ, ์ƒ)
22+
const directions = [[0,1], [1,0], [0,-1], [-1,0]];
23+
24+
let i = 0; // ์‹œ์ž‘ i ์ขŒํ‘œ
25+
let j = 0; // ์‹œ์ž‘ j ์ขŒํ‘œ
26+
let directionIndex = 0; // ์šฐ๋ฐฉํ–ฅ๋ถ€ํ„ฐ ์‹œ์ž‘
27+
28+
while (orderList.length < totalLength) {
29+
// ํ˜„์žฌ ์œ„์น˜๋ฅผ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ orderList์— ์ถ”๊ฐ€
30+
orderList.push(matrix[i][j])
31+
visited[i][j] = true;
32+
33+
// ๋‹ค์Œ ์œ„์น˜
34+
let nextI = i + directions[directionIndex][0];
35+
let nextJ = j + directions[directionIndex][1];
36+
37+
// ๋‹ค์Œ ์œ„์น˜๊ฐ€ ๋ฒ”์œ„ ๋‚ด์ด๊ณ  ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ๊ทธ ์œ„์น˜๋กœ ์ด๋™
38+
if (nextI >= 0 && nextI < matrix.length && nextJ >= 0 && nextJ < matrix[0].length && !visited[nextI][nextJ]) {
39+
i = nextI;
40+
j = nextJ;
41+
} else {
42+
// ๋‹ค์Œ ์œ„์น˜๊ฐ€ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜, ๋ฐฉ๋ฌธํ•œ ๊ฒฝ์šฐ ๋ฐฉํ–ฅ ๋ณ€๊ฒฝ
43+
directionIndex = (directionIndex + 1) % 4;
44+
i += directions[directionIndex][0];
45+
j += directions[directionIndex][1];
46+
}
47+
48+
}
49+
50+
return orderList;
51+
}
52+

0 commit comments

Comments
ย (0)