您的位置:首页 > 其它

[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 = 
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法