给定一个数n, 生成一个包含1~n^2 的螺旋形矩阵.
样例
样例 1:
输入: 2
输出:
[
[1, 2],
[4, 3]
]
样例 2:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
class Solution {
public:
/**
* @param n: An integer
* @return: a square matrix
*/
vector<vector<int>> generateMatrix(int n) {
// write your code here
vector<vector<int>>res(n,vector<int>(n,0));
int startrow=0;
int startcol=0;
int endrow=n-1;
int endcol=n-1;
int num=1;
int target=n*n;
while(num<=target)
{
for (int i = startcol; i <= endcol; i++) {
res[startrow][i]=num;
num++;
}
startrow++;
for (int i = startrow; i <= endrow; i++) {
res[i][endcol]=num;
num++;
}
endcol--;
for (int i = endcol; i >= startcol; i--) {
/* code */
res[endrow][i]=num;
num++;
}
endrow--;
for (int i = endrow; i >= startrow; i--) {
/* code */
res[i][startcol]=num;
num++;
}
startcol++;
}
return res;
}
};