Skip to content

Commit 8366313

Browse files
committed
feat: 54. Spiral Matrix
1 parent 93a584f commit 8366313

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

spiral-matrix/gwbaik9717.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// n: height of matrix, m: width of matrix
2+
// Time complexity: O(n*m)
3+
// Space complexity: O(n+m)
4+
5+
/**
6+
* @param {number[][]} matrix
7+
* @return {number[]}
8+
*/
9+
var spiralOrder = function (matrix) {
10+
const n = matrix.length;
11+
const m = matrix[0].length;
12+
13+
// order of direction: East, South, West, North
14+
const dy = [0, 1, 0, -1];
15+
const dx = [1, 0, -1, 0];
16+
17+
let dir = 0;
18+
let y = 0;
19+
let x = 0;
20+
21+
const answer = [];
22+
23+
while (true) {
24+
answer.push(matrix[y][x]);
25+
matrix[y][x] = "";
26+
27+
let ny = y + dy[dir];
28+
let nx = x + dx[dir];
29+
30+
if (ny >= 0 && ny < n && nx >= 0 && nx < m && matrix[ny][nx] !== "") {
31+
y = ny;
32+
x = nx;
33+
continue;
34+
}
35+
36+
// If the new position is out of bounds or already visited, Change direction
37+
dir = (dir + 1) % 4;
38+
39+
ny = y + dy[dir];
40+
nx = x + dx[dir];
41+
42+
// If the changed direction still has a problem, Break the loop
43+
if (ny < 0 || ny >= n || nx < 0 || nx >= m || matrix[ny][nx] === "") {
44+
break;
45+
}
46+
47+
y = ny;
48+
x = nx;
49+
}
50+
51+
return answer;
52+
};

0 commit comments

Comments
 (0)