[leetcode 59] Spiral Matrix II--------数组转圈赋值
2016-03-23 22:05
495 查看
Question:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:
分析:
题目很清楚,对数组转圈进行初始化,每次开始的点都是对角线上的点,但是需要判断,因为是转圈,所以只要走n/2圈即可。
因为矩阵是n*n,所以起点横坐标与纵坐标相等,一圈四个边,所以走四个遍历即可。注意判断循环中的起始点和结束点,与保存。
代码如下:
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 ] ]
分析:
题目很清楚,对数组转圈进行初始化,每次开始的点都是对角线上的点,但是需要判断,因为是转圈,所以只要走n/2圈即可。
因为矩阵是n*n,所以起点横坐标与纵坐标相等,一圈四个边,所以走四个遍历即可。注意判断循环中的起始点和结束点,与保存。
代码如下:
<span style="font-size:14px;">class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n,vector<int>(n)); if(n <= 0){ return res; } helper(res,0,n); return res; } void helper(vector<vector<int>>& res,int pos,int n){ if(pos > n/2) return ; int j,i; for(i = pos; i < n-pos; ++i){//上边的行 res[pos][i] = res[pos][i-1] + 1; } --i; for(j = pos + 1; j < n-pos; ++j){//右边的列 res[j][i] = res[j-1][i] + 1; } --j; for(i = i - 1; i >= pos; --i){//下边的行 res[j][i] = res[j][i+1] + 1; } ++i; for(j = j - 1; j > pos; --j){//左边的列 res[j][i] = res[j+1][i] + 1; } helper(res,pos+1,n); } };</span>
相关文章推荐
- EasyRecyclerView 添加header,footer, 上拉加载更多的recyclerview
- ExtJs之Ext.util.CSS
- web前端与后台数据访问的对象封装
- 极大点问题
- linux下weblogic 工程,Spring的Trigger定时器自动shut_down报错信息记录(暂时没有定位到问题)
- 欢迎使用CSDN-markdown编辑器
- Java虚拟机体系结构与类加载器委托机制
- java中的equals方法与"=="运算符解说
- SQL常见笔试面试题
- [原创] 用两个queue实现stack的功能
- Integer做WeakHashMap的Key应注意的问题
- CSS浮动
- 在kali linux206-01版本上安装vmtools一直不能用
- 我理解的--java 单例模式
- 去除tableview没数据时候的下边的线
- 802.11b的物理层
- 第4周项目4:程序分析(1)
- Linux内核协议栈(4) 跟踪sendto调用
- 网站性能优化
- SharePoint2010 IT Professional - Content Deployment