-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path054.js
More file actions
46 lines (40 loc) · 1.17 KB
/
054.js
File metadata and controls
46 lines (40 loc) · 1.17 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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
const rowCount = matrix.length;
if (rowCount === 0) return [];
const colCount = matrix[0].length;
if (colCount === 0) return [];
let topOffset = 0;
let bottomOffset = 0;
let leftOffset = 0;
let rightOffset = 0;
let result = [];
while(true) {
for(let i = leftOffset; i < colCount - rightOffset; ++i) {
result.push(matrix[topOffset][i]);
}
++topOffset;
if (topOffset + bottomOffset >= rowCount) break;
let col = colCount - 1 - rightOffset;
for(let i = topOffset; i < rowCount - bottomOffset; ++i) {
result.push(matrix[i][col]);
}
++rightOffset;
if (leftOffset + rightOffset >= colCount) break;
let row = rowCount - 1 - bottomOffset;
for (let i = colCount - 1 - rightOffset; i >= leftOffset; --i) {
result.push(matrix[row][i]);
}
++bottomOffset;
if (topOffset + bottomOffset >= rowCount) break;
for (let i = rowCount - 1 - bottomOffset; i >= topOffset; --i) {
result.push(matrix[i][leftOffset]);
}
++leftOffset;
if (leftOffset + rightOffset >= colCount) break;
}
return result;
};