题目链接
tag:
- Medium;
question:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路:
此题跟之前那道 Spiral Matrix 本质上没什么区别,就相当于个类似逆运算的过程,这道题是要按螺旋的顺序来填数,代码如下:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int up = 0, down = n - 1, left = 0, right = n - 1, val =1;
while (true) {
for (int i=left; i<=right; ++i) res[up][i] = val++;
if (++up > down) break;
for (int i=up; i<=down; ++i) res[i][right] = val++;
if (--right < left) break;
for (int i=right; i>=left; --i) res[down][i] = val++;
if (--down < up) break;
for (int i=down; i>=up; --i) res[i][left] = val++;
if (++left > right) break;
}
return res;
}
};