|
| 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