描述
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 ]
]
返回一个螺旋输出是 1,2,3,... 的二维数组。
分析
这道题是Spiral Matrix 的变形,但其实比原题要简单,因为已经知道了二维数组的行和列都是 n <script type="math/tex" id="MathJax-Element-273">n</script> ,因此我们只需要按照螺旋顺序,依次在二维数组中填充相应的数字就可以了。具体的螺旋顺序的遍历请看 这里 。
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> tmp(n, 0);
vector<vector<int>> res(n, tmp);
int row = -1, col = -1, run = 0;
for (int i = 1; i <= n * n;) {
for (row++, col++; col < n - run; col++) res[row][col] = i++;
for (row++, col--; row < n - run; row++) res[row][col] = i++;
for (col--, row--; col >= run; col--) res[row][col] = i++;
for (row--, col++; row > run; row--) res[row][col] = i++;
run++;
}
return res;
}
};