[leetcode] Spiral Matrix II
2014-08-09 17:28
387 查看
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:
思路:一层一层遍历,逐步生成数字
代码:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > res;
if(n==0) return res;
vector<int> temp;
for(int i=0;i<n;i++){
temp.clear();
for(int j=0;j<n;j++){
temp.push_back(1);
}
res.push_back(temp);
}
int t=1;
for(int layer=0;layer<n/2;layer++){
for(int i=layer;i<n-layer-1;i++){
res[layer][i]=t;
t++;
}
for(int i=layer;i<n-layer-1;i++){
res[i][n-layer-1]=t;
t++;
}
for(int i=n-layer-2;i>=layer;i--){
res[n-layer-1][i+1]=t;
t++;
}
for(int i=n-layer-2;i>=layer;i--){
res[i+1][layer]=t;
t++;
}
}
if(n%2!=0) res[n/2][n/2]=n*n;
return res;
}
};
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路:一层一层遍历,逐步生成数字
代码:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > res;
if(n==0) return res;
vector<int> temp;
for(int i=0;i<n;i++){
temp.clear();
for(int j=0;j<n;j++){
temp.push_back(1);
}
res.push_back(temp);
}
int t=1;
for(int layer=0;layer<n/2;layer++){
for(int i=layer;i<n-layer-1;i++){
res[layer][i]=t;
t++;
}
for(int i=layer;i<n-layer-1;i++){
res[i][n-layer-1]=t;
t++;
}
for(int i=n-layer-2;i>=layer;i--){
res[n-layer-1][i+1]=t;
t++;
}
for(int i=n-layer-2;i>=layer;i--){
res[i+1][layer]=t;
t++;
}
}
if(n%2!=0) res[n/2][n/2]=n*n;
return res;
}
};
相关文章推荐
- Leetcode59 Spiral Matrix II
- LeetCode - Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [LeetCode]59. Spiral Matrix II
- LeetCode Spiral Matrix II
- LeetCode Spiral Matrix II
- [LeetCode]Spiral Matrix II
- Spiral Matrix II ---leetcode
- [LeetCode] Spiral Matrix II
- Leetcode 54 spiral matrix II (螺旋矩阵)
- [LeetCode] Spiral Matrix II
- Leetcode Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- LeetCode(59)SPiral Matrix II
- leetcode 日经贴,Cpp code -Spiral Matrix II
- Leetcode: Spiral Matrix II
- LeetCode-Spiral Matrix II