Skip to content

Commit a23b16b

Browse files
committed
Spiral Matrix Solution
1 parent 4067e25 commit a23b16b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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

Comments
ย (0)