您的位置:首页 > 其它

Spiral Matrix II

2015-08-24 20:50 459 查看
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 ]
]


Solution:

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > res;
if(n <= 0) return res;
res.resize(n);
for(int i = 0; i < n; ++i) res[i].resize(n);
int lu = 0, rd = n - 1, k = 0;
while(lu <= rd)
{
for(int i = lu; i <= rd; ++i) res[lu][i] = ++k;
for(int i = lu + 1; i <= rd; ++i) res[i][rd] = ++k;
for(int i = rd - 1; i >= lu; --i) res[rd][i] = ++k;
for(int i = rd - 1; i > lu; --i) res[i][lu] = ++k;
lu++;
rd--;
}

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: