-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path59.spiral-matrix-ii.js
57 lines (53 loc) · 1.02 KB
/
59.spiral-matrix-ii.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
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=59 lang=javascript
*
* [59] Spiral Matrix II
*/
// @lc code=start
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
let xlb = 0,
xub = n - 1;
let ylb = 0,
yub = n - 1;
let result = [];
for (let i = 0; i < n; i++) {
result.push([]);
}
let target = Math.pow(n, 2),
current = 1;
while (current <= target) {
if (ylb <= yub) {
for (let i = xlb; i <= xub; i++) {
result[ylb][i] = current++;
}
ylb++;
}
if (xlb <= xub) {
for (let i = ylb; i <= yub; i++) {
result[i][xub] = current++;
}
xub--;
}
if (ylb <= yub) {
for (let i = xub; i >= xlb; i--) {
result[yub][i] = current++;
}
yub--;
}
if (xlb <= xub) {
for (let i = yub; i >= ylb; i--) {
result[i][xlb] = current++;
}
xlb++;
}
}
return result;
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = generateMatrix;
// @after-stub-for-debug-end