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 ]
For example, Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
property: 正方形,上下、左右的长度是一样的,上下界都是start, end。有了四个方向上的界,四条边就确定了。顺时针填完四个边,四个方向上的界都缩一个单位,也就是start++, end--
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> output(n,vector<int>(n));
int begin = 0, end =n-1, num=1;
while(begin<end)
{
for(int j=begin;j<end;j++) output[begin][j]=num++;
for(int i=begin;i<end;i++) output[i][end]=num++;
for(int j=end;j>begin;j--) output[end][j]=num++;
for(int i=end;i>begin;i--) output[i][begin]=num++;
begin++;end--;
}
if(begin==end)
output[begin][end]=num;
return output;
}

815

被折叠的 条评论
为什么被折叠?



