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 ]
]
AC代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n);
for (auto& row : ans) row.resize(n);
int q = n * n + 1, l = 0, r = n - 1, u = 0, d = n - 1, cnt = 1, i = 0, j = 0;
while (true) {
while (j <= r) ans[i][j++] = cnt++;
j--;
i++;
u++;
if (cnt == q) break;
while (i <= d) ans[i++][j] = cnt++;
i--;
j--;
r--;
if (cnt == q) break;
while (j >= l) ans[i][j--] = cnt++;
j++;
i--;
d--;
if (cnt == q) break;
while (i >= u) ans[i--][j] = cnt++;
i++;
j++;
l++;
if (cnt == q) break;
}
return ans;
}
};
总结
简单粗暴的解法