[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; };
相关文章推荐
- Javascript中的依赖注入
- [LeetCode][JavaScript]Spiral Matrix
- js动态控制多选框的选中项
- JSP表单提交中文乱码
- JavaScript高级程序设计之面向对象的程序设计之创建对象之原型模式 第6.2.3讲笔记
- HTML5 JS API 本地存储LocalStorage基本操作
- "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")"的分析
- Json数据解析
- JSON.stringify()JSON转字符串 和 JSON.parse()字符串转JSON对象
- js最新手机号码、身份证正则表达式
- Servlet、JSP学习总结
- javascript dom读取xml
- JSON数据转换
- JavaScript高级程序设计之面向对象的程序设计之创建对象之 构造函数模式第6.2.2讲笔记
- JavaScript高级程序设计之面向对象的程序设计之创建对象之工厂模式第6.2.1讲笔记
- javascript中的array对象属性及方法
- javascript中的算数运算
- 标 题: JavaScript真的要一统江湖了
- json学习初体验--第三者jar包实现bean、List、map创json格式
- javascript中的数据类型---数字