Skip to content

Commit ebe936c

Browse files
committed
spiral matrix solution
1 parent db563ea commit ebe936c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

โ€Žspiral-matrix/byol-han.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* https://leetcode.com/problems/spiral-matrix/
3+
* @param {number[][]} matrix
4+
* @return {number[]}
5+
*/
6+
var spiralOrder = function (matrix) {
7+
const result = [];
8+
if (matrix.length === 0) return result;
9+
10+
let top = 0;
11+
let bottom = matrix.length - 1;
12+
let left = 0;
13+
let right = matrix[0].length - 1;
14+
15+
while (top <= bottom && left <= right) {
16+
// 1. ์ขŒ -> ์šฐ
17+
for (let col = left; col <= right; col++) {
18+
result.push(matrix[top][col]);
19+
}
20+
top++; // ์œ„์ชฝ ๊ฒฝ๊ณ„ ํ•œ ์ค„ ์•„๋ž˜๋กœ ์ด๋™
21+
22+
// 2. ์œ„ -> ์•„๋ž˜
23+
for (let row = top; row <= bottom; row++) {
24+
result.push(matrix[row][right]);
25+
}
26+
right--; // ์˜ค๋ฅธ์ชฝ ๊ฒฝ๊ณ„ ์™ผ์ชฝ์œผ๋กœ ์ด๋™
27+
28+
// 3. ์šฐ -> ์ขŒ
29+
if (top <= bottom) {
30+
for (let col = right; col >= left; col--) {
31+
result.push(matrix[bottom][col]);
32+
}
33+
bottom--; // ์•„๋ž˜์ชฝ ๊ฒฝ๊ณ„ ์œ„๋กœ ์ด๋™
34+
}
35+
36+
// 4. ์•„๋ž˜ -> ์œ„
37+
if (left <= right) {
38+
for (let row = bottom; row >= top; row--) {
39+
result.push(matrix[row][left]);
40+
}
41+
left++; // ์™ผ์ชฝ ๊ฒฝ๊ณ„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™
42+
}
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
ย (0)