-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy path0054_spiral_matrix_(medium).js
More file actions
70 lines (64 loc) · 1.45 KB
/
Copy path0054_spiral_matrix_(medium).js
File metadata and controls
70 lines (64 loc) · 1.45 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* 54. Spiral Matrix
*
* https://leetcode.com/problems/spiral-matrix/
*
* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
*
* For example,
* Given the following matrix:
*
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* You should return [1,2,3,6,9,8,7,4,5].
*/
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = (matrix) => {
const result = [];
if (!matrix || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
let m = matrix.length;
let n = matrix[0].length;
const layers = Math.ceil(Math.min(m, n) / 2);
for (let k = 0; k < layers; k++, m -= 2, n -= 2) {
if (m <= 0 || n <= 0) {
break;
}
if (m === 1) {
// only has one row
for (let j = 0; j < n; j++) {
result.push(matrix[k][k + j]);
}
} else if (n === 1) {
// only has one column
for (let i = 0; i < m; i++) {
result.push(matrix[k + i][k]);
}
} else {
// top
for (let j = 0; j < n - 1; j++) {
result.push(matrix[k][k + j]);
}
// right
for (let i = 0; i < m - 1; i++) {
result.push(matrix[k + i][k + n - 1]);
}
// bottom
for (let j = n - 1; j > 0; j--) {
result.push(matrix[k + m - 1][k + j]);
}
// left
for (let i = m - 1; i > 0; i--) {
result.push(matrix[k + i][k]);
}
}
}
return result;
};