Skip to content

Commit f50fe1f

Browse files
committed
feat: 문제풀이 추가
1 parent 37ed176 commit f50fe1f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

spiral-matrix/hwanmini.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 시간복잡도 O(n * m)
2+
// 공간복잡도 O(n * m)
3+
4+
const isVisited = (matrix, row, col) => {
5+
return matrix[row][col] === '#'
6+
}
7+
8+
/**
9+
* @param {number[][]} matrix
10+
* @return {number[]}
11+
*/
12+
var spiralOrder = function(matrix) {
13+
const result = []
14+
15+
const colLen = matrix[0].length;
16+
const rowLen = matrix.length
17+
18+
let direction = 'right'
19+
let row = 0;
20+
let col = 0;
21+
while (result.length < colLen * rowLen ) {
22+
result.push(matrix[row][col])
23+
matrix[row][col] = '#'
24+
25+
if (direction === 'right') {
26+
if (isVisited(matrix, row, col+1) || col === colLen - 1) {
27+
direction = 'down'
28+
row++
29+
} else {
30+
col++
31+
}
32+
} else if (direction === 'down') {
33+
if ((row + 1 < rowLen && isVisited(matrix, row+1, col) || row === rowLen - 1)) {
34+
direction = 'left'
35+
col--
36+
} else {
37+
row++
38+
}
39+
} else if (direction === 'left') {
40+
if ((col > 0 && isVisited(matrix, row, col-1) || col === 0)) {
41+
direction = 'up'
42+
row--
43+
} else {
44+
col--
45+
}
46+
} else if (direction === 'up') {
47+
if ( (row > 0 && isVisited(matrix,row-1, col))) {
48+
direction = 'right'
49+
col++
50+
} else {
51+
row--
52+
}
53+
}
54+
55+
}
56+
57+
return result
58+
};
59+
60+
61+
62+
console.log(spiralOrder([
63+
[1,2,3],
64+
[4,5,6],
65+
[7,8,9]])) // [1,2,3,6,9,8,7,4,5]
66+

0 commit comments

Comments
 (0)