[LeetCode101]Spiral Matrix2
来源:互联网 发布:手机运行ubuntu 编辑:程序博客网 时间:2024/06/15 19:34
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]Analysis:
Similiar with the former one Spiral Matrix
Java
public int[][] generateMatrix(int n) { int [][] result = new int[n][n]; int x1=0; int y1=0; int x2=n-1; int y2 = n-1; int val = 1; while(x1<=x2 && y1<=y2){ for(int i=y1;i<=y2;i++) result[x1][i] = val++; for(int j = x1+1;j<=x2;j++) result[j][y2] = val++; if(x1!=x2) for(int i=y2-1;i>=y1;i--) result[x2][i] = val++; if(y1!=y2) for(int j=x2-1;j>y1;j--) result[j][y1]=val++; x1++;y1++;x2--;y2--; } return result; }
c++
vector<vector<int> > generateMatrix(int n) { vector<vector<int>> matrix(n); if(n == 0) return matrix; for(int i=0; i<n; i++){ matrix[i].resize(n); } int x1 = 0; int y1 = 0; int x2 = n - 1; int y2 = n - 1; int val = 1; while(x1<=x2 && y1<=y2){ for(int j = y1; j<=y2; ++j) matrix[x1][j] = val++; for(int i = x1+1; i<=x2; ++i) matrix[i][y2] = val++; if(x2 !=x1) for(int j = y2-1; j>=y1; --j) matrix[x2][j] = val++; if(y2 != y1) for(int i = x2-1; i>x1; --i) matrix[i][y1] = val++; x1++, y1++, x2--, y2--; } return matrix; }
0 0
- [LeetCode101]Spiral Matrix2
- matrix2
- leetcode101.SymmetricTree
- spiral
- LeetCode101 SynmetricTree Java题解
- LeetCode101—Symmetric Tree
- LeetCode101 Symmetric Tree
- LeetCode101. Symmetric Tree
- leetcode101~Symmetric Tree
- leetcode101 Symmetric Tree
- LeetCode101. Symmetric Tree题解
- LeetCode101 Symmetric Tree
- LeetCode101. Symmetric Tree
- leetcode101. Symmetric Tree
- LeetCode101. Symmetric Tree
- LeetCode101. Symmetric Tree
- SPOJ 912 MATRIX2(二维单调队列)
- LeetCode101——Symmetric Tree
- Android开源图表库XCL-Charts版本发布及展示页
- SVM入门(八)松弛变量
- 第二周__“RSA”、“数字签名”、“公钥”、“DES”等4个名词的解释以及公钥加密 与 数字签名 之间的联系与区别
- 不同Activity之间的动画切换
- SVM入门(九)松弛变量(续)
- [LeetCode101]Spiral Matrix2
- 对于MVC模式的理解
- 【leetcode】Flatten Binary Tree to Linked List
- 文本分类入门
- java将数据库内容生成Excel表
- libsvm中的dec_values以及分类结果评分问题
- LetterView实现加载全国各地城市
- Alibaba最新组织架构图
- nfs:server ***** not responding, still trying