Skip to content

Commit fffc8e1

Browse files
committed
5. Spiral Matrix
1 parent 06ac2fa commit fffc8e1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

spiral-matrix/sunjae95.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* just implement question
5+
*
6+
* m: length of matrix
7+
* n: length of matrix[i]
8+
* time complexity: O(m * n)
9+
* space complexity: O(m * n)
10+
*/
11+
var spiralOrder = function (matrix) {
12+
let count = matrix.length * matrix[0].length;
13+
let [r, c] = [1, 1];
14+
const answer = [];
15+
const MAX_R = matrix.length + 2;
16+
const MAX_C = matrix[0].length + 2;
17+
const visited = Array.from({ length: MAX_R }, (_, i) => {
18+
return Array.from(
19+
{ length: MAX_C },
20+
(_, j) => i === 0 || i === MAX_R - 1 || j === 0 || j === MAX_C - 1
21+
);
22+
});
23+
24+
while (count--) {
25+
const check = {
26+
left: c >= 1 && visited[r][c - 1],
27+
right: c < MAX_C - 1 && visited[r][c + 1],
28+
top: r >= 1 && visited[r - 1][c],
29+
bottom: r < MAX_R - 1 && visited[r + 1][c],
30+
};
31+
visited[r][c] = true;
32+
answer.push(matrix[r - 1][c - 1]);
33+
34+
if (check.left && check.top && check.bottom) c++;
35+
else if (check.left && check.top && check.right) r++;
36+
else if (check.right && check.top && check.bottom) c--;
37+
else if (check.left && check.right && check.bottom) r--;
38+
else if (check.left && check.top) c++;
39+
else if (check.top && check.right) r++;
40+
else if (check.right && check.bottom) c--;
41+
else if (check.bottom && check.left) r--;
42+
}
43+
44+
return answer;
45+
};

0 commit comments

Comments
 (0)