[LeetCode][JavaScript]Spiral Matrix II

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
https://leetcode.com/problems/spiral-matrix-ii/
 
 
 

 
 
每做完一条边,就缩小对应长或宽的范围。
 1 /**
 2  * @param {number} n
 3  * @return {number[][]}
 4  */
 5 var generateMatrix = function(n) {
 6     var res = [], i , j, count = 1;
 7     for(i = 0; i < n; i++){
 8         res[i] = [];
 9         for(j = 0; j < n; j++){
10             res[i].push(0);
11         } 
12     }
13     var heightStart = widthStart = 0, heightEnd = widthEnd = n - 1;
14     n = Math.ceil(n / 2);
15     while(n--){
16         for(i = widthStart; i <= widthEnd; i++){
17             res[heightStart][i] = count++;
18         }
19         heightStart++;
20         for(i = heightStart; i <= heightEnd; i++){
21             res[i][widthEnd]  = count++;
22         }
23         widthEnd--;
24         for(i = widthEnd; i >= widthStart; i--){
25             res[heightEnd][i] = count++;
26         }
27         heightEnd--;
28         for(i = heightEnd; i >= heightStart; i--){
29             res[i][widthStart]  = count++;
30         }
31         widthStart++;
32     }
33     return res;
34 };
 
 
原文地址:https://www.cnblogs.com/Liok3187/p/4842345.html