码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Spiral Matrix II

时间:2015-09-27 17:21:04      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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     }
34     return res;
35 };

 

 
 

 

[LeetCode][JavaScript]Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4842345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!