59.Spiral Matrix II
2015-06-25 14:59
295 查看
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:
solution1
solution2
与顺时针打印矩阵算是相反的问题
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
solution1
class Solution { public: vector<vector<int> > generateMatrix(int n) { if(n == 0) return vector<vector<int>>(); vector<vector<int>> ret(n, vector<int>(n, 0)); int rowBegin = 0; int rowEnd = n - 1; int colBegin = 0; int colEnd = n - 1; int num = 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { if (num <= n^2) { //向右遍历添加 for (int j = colBegin; j <= colEnd; j++) { ret[rowBegin][j] = num; num++; } } rowBegin++; if (num <= n^2) { //向下遍历添加 for (int i = rowBegin; i <= rowEnd; i++) { ret[i][colEnd] = num; num++; } } colEnd--; if (num <= n^2) { //向左遍历添加 for (int j = colEnd; j >= colBegin; j--) { ret[rowEnd][j] = num; num++; } } rowEnd--; if (num <= n^2) { //向上遍历添加 for (int i = rowEnd; i >= rowBegin; i--) { ret[i][colBegin] = num; num++; } } colBegin++; } return ret; } };
solution2
与顺时针打印矩阵算是相反的问题
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ret; ret.resize(n); for (int i = 0;i<ret.size();++i) { ret[i].resize(n,0); } int start = 0; int num = 1; while (n>2*start) { constructMatrixOnce(ret,n,start++,num); } return ret; } void constructMatrixOnce(vector<vector<int>> &ret ,int n,int start,int& num) { int endX = n-start-1; int endY = n-start-1; for(int i = start;i<=endX;++i) { ret[start][i] = num++; } if(start<endY) { for(int i = start+1;i<=endY;++i) { ret[i][endX] = num++; } } if(start<endY && start<endX) { for(int i = endX-1;i>=start;--i) { ret[endY][i] = num++; } } if(start<endX && endY-start>1) { for(int i = endY-1;i>=start+1;--i) { ret[i][start] = num++; } } } };
相关文章推荐
- int类型取值范围
- NSString什么时候用copy,什么时候用strong
- linux自动重启tomcat脚本
- android activity切换效果实现
- RecyclerView使用介绍
- [Flash 3D] 又是一个难题解决了。(Flash3D在android中运行)
- HTTP状态码的含义
- Linux 7.2 iptables
- 6.25 被虐记 6 期末测试 变相求和
- 机器学习中的范数规则化之(二)核范数与规则项参数选择
- C#/IOS/Android通用加密解密方法
- BZOJ3884 上帝与集合的正确用法
- POJ 3210 : Coins
- upper_bound和lower_bound的用法
- 编写一个排序函数,实现数字排序。排序方法由客户函数实现,函数参数个数为两个,两个参数的关系作为排序后的元素间的关系。
- POJ 3210 : Coins
- 变量存储类型
- iPhone的技术能力是如何领军业界的?
- Binary Tree Inorder Traversal
- OKHttp源码解析