59. 螺旋矩阵 II
题目描述:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思想:
上->右->下->左 循环赋值
代码:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n); for (int i = 0; i < ans.size(); i++) //注意先设定好ans的size ans[i].resize(n); int num = n * n; int i = 1; int l = 0; int r = n - 1; int u = 0; int d = n - 1; while (i <= num) { for (int j = l; j <= r && i <= num; i++, j++) ans[u][j] = i; u++; for (int j = u; j <= d && i <= num; i++, j++) ans[j][r] = i; r--; for (int j = r; j >= l && i <= num; i++, j--) ans[d][j] = i; d--; for (int j = d; j >= u && i <= num; i++, j--) ans[j][l] = i; l++; } return ans; } };