-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
45 lines (39 loc) · 1.05 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let m = matrix.length
if (m == 0) return []
let n = matrix[0].length,
res = [],
i = j = 0,
topLimit = leftLimit = 0,
bottomLimit = m - 1,
rightLimit = n - 1,
xDirection = 1,
yDirection = 0
for (let c = 0; c < m * n; c++) {
res.push(matrix[i][j])
if (j + xDirection > rightLimit) {
topLimit = i + 1
xDirection = 0
yDirection = 1
} else if (i + yDirection > bottomLimit) {
rightLimit = j - 1
xDirection = -1
yDirection = 0
} else if (j + xDirection < leftLimit) {
bottomLimit = i - 1
xDirection = 0
yDirection = -1
} else if (i + yDirection < topLimit) {
leftLimit = j + 1
xDirection = 1
yDirection = 0
}
i += yDirection
j += xDirection
}
return res
};