您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Spiral Matrix II

2015-09-27 16:06 741 查看

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/

跟上一题一样的思路:/article/7171030.html
每做完一条边,就缩小对应长或宽的范围。

/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
var res = [], i , j, count = 1;
for(i = 0; i < n; i++){
res[i] = [];
for(j = 0; j < n; j++){
res[i].push(0);
}
}
var heightStart = widthStart = 0, heightEnd = widthEnd = n - 1;
n = Math.ceil(n / 2);
while(n--){
for(i = widthStart; i <= widthEnd; i++){
res[heightStart][i] = count++;
}
heightStart++;
for(i = heightStart; i <= heightEnd; i++){
res[i][widthEnd]  = count++;
}
widthEnd--;
for(i = widthEnd; i >= widthStart; i--){
res[heightEnd][i] = count++;
}
heightEnd--;
for(i = heightEnd; i >= heightStart; i--){
res[i][widthStart]  = count++;
}
widthStart++;
}
return res;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: