Spiral Matrix II
2015-08-24 20:50
459 查看
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:
Solution:
n2 in spiral order.
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Solution:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int> > res; if(n <= 0) return res; res.resize(n); for(int i = 0; i < n; ++i) res[i].resize(n); int lu = 0, rd = n - 1, k = 0; while(lu <= rd) { for(int i = lu; i <= rd; ++i) res[lu][i] = ++k; for(int i = lu + 1; i <= rd; ++i) res[i][rd] = ++k; for(int i = rd - 1; i >= lu; --i) res[rd][i] = ++k; for(int i = rd - 1; i > lu; --i) res[i][lu] = ++k; lu++; rd--; } return res; } };
相关文章推荐
- Logback使用以及与log4j区别
- Unity_使用EasyTouch插件碰撞检测失效的解决方法
- 如何移除原生tabBar
- 求多个列的最大值/最小值
- 谈谈Java中的集合
- (转)st(state-threads) coroutine调度
- css3选择器
- bash shell基础特性之二
- android listView 间距
- boost条件变量和互斥使用例子
- android 串口扩展(wk2xxx)移植
- HTML常用标签
- Singleton模式线程相关的(C\C++)
- Android API Guides 安卓API指导----第一部分:Introduction(介绍)
- HDU2089 不要62(数位DP入门经典题目)
- HDU2389 Rain on your Parade(二分图匹配 ,HK算法 )
- 怎样的突破洗脑?
- launchMode 的四种启动方式
- html5新增语义标签
- Google Java编程风格指南