|
| 1 | +/** |
| 2 | + * ์ค๋ฅธ์ชฝ -> ์๋์ชฝ -> ์ผ์ชฝ -> ์์ชฝ |
| 3 | + * --- ํ๋ ฌ์ ๊ฒฝ๊ณ --- |
| 4 | + * top: ์์ชฝ ๊ฒฝ๊ณ |
| 5 | + * bottom: ์๋์ชฝ ๊ฒฝ๊ณ |
| 6 | + * left: ์ผ์ชฝ ๊ฒฝ๊ณ |
| 7 | + * right: ์ค๋ฅธ์ชฝ ๊ฒฝ๊ณ |
| 8 | + * ---------------- |
| 9 | + * ๊ฐ ๋ฐฉํฅ์ผ๋ก ํ ๋ฐํด๋ฅผ ๋ ๋๋ง๋ค ๊ฒฝ๊ณ๋ฅผ ํ๋์ฉ ์ค์ฌ๊ฐ๋ฉฐ ๋ชจ๋ ์์๋ฅผ ๋ฐฉ๋ฌธ |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * @param {number[][]} matrix |
| 14 | + * @return {number[]} |
| 15 | + */ |
| 16 | +var spiralOrder = function (matrix) { |
| 17 | + if (!matrix.length || !matrix[0].length) return []; // ๋น ํ๋ ฌ ์ฒดํฌ |
| 18 | + |
| 19 | + const result = []; // ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฐฐ์ด ์ด๊ธฐํ |
| 20 | + |
| 21 | + let top = 0; |
| 22 | + let bottom = matrix.length - 1; |
| 23 | + let left = 0; |
| 24 | + let right = matrix[0].length - 1; |
| 25 | + |
| 26 | + // ์์ง ์ฒ๋ฆฌํ ์์๊ฐ ๋จ์์๋ ๋์ ๊ณ์ ์ํ |
| 27 | + // top > bottom ๋๋ left > right๊ฐ ๋๋ฉด ๋ชจ๋ ์์๋ฅผ ๋ฐฉ๋ฌธํ ๊ฒ |
| 28 | + while (top <= bottom && left <= right) { |
| 29 | + // 1. ์์ชฝ ํ: ์ผ์ชฝ โ ์ค๋ฅธ์ชฝ ์ด๋ |
| 30 | + for (let i = left; i <= right; i++) { |
| 31 | + result.push(matrix[top][i]); |
| 32 | + } |
| 33 | + // ์์ชฝ ํ์ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก top ์ธ๋ฑ์ค๋ฅผ 1 ์ฆ๊ฐ |
| 34 | + top++; |
| 35 | + |
| 36 | + // 2. ์ค๋ฅธ์ชฝ ์ด: ์ โ ์๋ ์ด๋ |
| 37 | + for (let i = top; i <= bottom; i++) { |
| 38 | + result.push(matrix[i][right]); |
| 39 | + } |
| 40 | + // ์ค๋ฅธ์ชฝ ์ด์ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก right ์ธ๋ฑ์ค๋ฅผ 1 ๊ฐ์ |
| 41 | + right--; |
| 42 | + |
| 43 | + // 3. ์๋์ชฝ ํ: ์ค๋ฅธ์ชฝ โ ์ผ์ชฝ ์ด๋ |
| 44 | + // ์ด๋ฏธ top์ด bottom์ ์ด๊ณผํ ๊ฒฝ์ฐ, ์๋์ชฝ ํ์ด ์กด์ฌํ์ง ์์ผ๋ฏ๋ก ์ฒ๋ฆฌํ์ง ์์ |
| 45 | + if (top <= bottom) { |
| 46 | + // ํ์ฌ bottom ํ์์ right๋ถํฐ left๊น์ง์ ๋ชจ๋ ์์๋ฅผ ์ญ์์ผ๋ก ์ํ |
| 47 | + for (let i = right; i >= left; i--) { |
| 48 | + result.push(matrix[bottom][i]); |
| 49 | + } |
| 50 | + // ์๋์ชฝ ํ์ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก bottom ์ธ๋ฑ์ค๋ฅผ 1 ๊ฐ์ |
| 51 | + bottom--; |
| 52 | + } |
| 53 | + |
| 54 | + // 4. ์ผ์ชฝ ์ด: ์๋ โ ์ ์ด๋ |
| 55 | + // ์ด๋ฏธ left๊ฐ right๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ, ์ผ์ชฝ ์ด์ด ์กด์ฌํ์ง ์์ผ๋ฏ๋ก ์ฒ๋ฆฌํ์ง ์์ |
| 56 | + if (left <= right) { |
| 57 | + // ํ์ฌ left ์ด์์ bottom๋ถํฐ top๊น์ง์ ๋ชจ๋ ์์๋ฅผ ์ญ์์ผ๋ก ์ํ |
| 58 | + for (let i = bottom; i >= top; i--) { |
| 59 | + result.push(matrix[i][left]); |
| 60 | + } |
| 61 | + // ์ผ์ชฝ ์ด์ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก left ์ธ๋ฑ์ค๋ฅผ 1 ์ฆ๊ฐ |
| 62 | + left++; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return result; |
| 67 | +}; |
0 commit comments