Skip to content

Commit 2bf04ed

Browse files
author
luzhipeng
committed
feat: 每日一题答案
1 parent e922e6f commit 2bf04ed

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: daily/answers/54.spiral-matrix.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* @lc app=leetcode id=54 lang=javascript
3+
*
4+
* [54] Spiral Matrix
5+
*/
6+
/**
7+
* @param {number[][]} matrix
8+
* @return {number[]}
9+
*/
10+
var spiralOrder = function(matrix) {
11+
// https://leetcode.com/problems/spiral-matrix/discuss/20570/Clean-Java-readable-human-friendly-code
12+
// brilliant!
13+
const res = [];
14+
if (matrix.length == 0) return res;
15+
16+
let top = 0;
17+
let bottom = matrix.length - 1;
18+
let left = 0;
19+
let right = matrix[0].length - 1;
20+
21+
while (true) {
22+
for (let i = left; i <= right; i++) res.push(matrix[top][i]);
23+
top++;
24+
if (top > bottom) break;
25+
26+
for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
27+
right--;
28+
if (left > right) break;
29+
30+
for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);
31+
bottom--;
32+
if (top > bottom) break;
33+
34+
for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
35+
left++;
36+
if (left > right) break;
37+
}
38+
39+
return res;
40+
};

0 commit comments

Comments
 (0)