您的位置:首页 > 其它

59. Spiral Matrix II

2016-08-21 15:59 399 查看

Problem

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) {
int begin = 0, end = n - 1;
vector<vector<int> > ret (n, vector<int>(n, 0));
int num = 1;
while(begin < end) {
for(int i = begin; i < end; ++i) ret[begin][i] = num++;
for(int i = begin; i < end; ++i) ret[i][end] = num++;
for(int i = end; i > begin; --i) ret[end][i] = num++;
for(int i = end; i > begin; --i) ret[i][begin] = num++;

++begin;
--end;
}
if(begin == end) {
ret[begin][begin] = num;
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: