[leetcode] 59.Spiral Matrix II
2015-08-26 23:14
459 查看
题目:
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*n的数组,让1到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*n的数组,让1到n* n的数字按照顺时针存放。
以上。
代码如下:
class Solution { public: vector<vector<int> > generateMatrix(int n) { if(n==0)return vector<vector<int> >(); vector<vector<int> >result(n, vector<int>(n,0)); int square = n * n; int num = 1; int x = 0, y = 0; while(num <= square) { while(y < n && result[x][y] == 0) { result[x][y] = num; y++; num++; } y--; x++; while(x < n && result[x][y] == 0) { result[x][y] = num; x++; num++; } x--; y--; while(y >= 0 && result[x][y] == 0) { result[x][y] = num; y--; num++; } x--; y++; while(x >= 0 && result[x][y] == 0 ) { result[x][y] = num; x--; num++; } x++; y++; } return result; } };
相关文章推荐
- SQL基础总结
- leetcode 209: Minimum Size Subarray Sum
- 变量使用
- 找工作---面试3
- UISlider
- idea自动生成serialVersionUID
- js类的静态属性应该如何抽象?
- ListView 异步加载头像与ListView批量加载的实现
- MVVMLight的使用方法
- linux虚拟机ping 总显示From 192.168.4.211: icmp_seq=2 Redirect Network(New nexthop: 192.168.4.1)
- ListView详解之三
- HDFS源码分析(六)-----租约
- artDialog使用
- STM32 Timer : Auto-reload register register
- 项目实战一 - 安卓数据库的设计(一 创建类)
- twisted-credentials
- JVM内存模型及垃圾回收机制
- Java多线程 -- 阻塞队列
- Linux环境编程
- Codeforces 235E Number Challenge (神定理+莫比乌斯反演)