Skip to content

Commit e2dccdc

Browse files
committed
spiral-matrix solution
1 parent b40ab33 commit e2dccdc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

spiral-matrix/lhc0506.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[]}
4+
*/
5+
var spiralOrder = function(matrix) {
6+
if (matrix.length === 0) return [];
7+
8+
const result = [];
9+
const rows = matrix.length;
10+
const cols = matrix[0].length;
11+
12+
let top = 0, bottom = rows - 1, left = 0, right = cols - 1;
13+
14+
while (top <= bottom && left <= right) {
15+
for (let i = left; i <= right; i++) {
16+
result.push(matrix[top][i]);
17+
}
18+
top += 1;
19+
20+
for (let i = top; i <= bottom; i++) {
21+
result.push(matrix[i][right]);
22+
}
23+
right -= 1;
24+
25+
if (top <= bottom) {
26+
for (let i = right; i >= left; i--) {
27+
result.push(matrix[bottom][i]);
28+
}
29+
bottom -= 1;
30+
}
31+
32+
if (left <= right) {
33+
for (let i = bottom; i >= top; i--) {
34+
result.push(matrix[i][left]);
35+
}
36+
left += 1;
37+
}
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)