给定一个正整数 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> > res(n, vector<int>(n, 0));
int left = 0;
int up = 0;
int right = n - 1;
int down = n - 1;
int cnt = 1;
while(up <= down && left <= right)
{
for(int i = left; i <= right; i++)
res[up][i] = cnt++;
up++;
if(up > down)
break;
for(int i = up; i <= down; i++)
res[i][right] = cnt++;
right--;
if(left > right)
break;
for(int i = right; i >= left; i--)
res[down][i] = cnt++;
down--;
if(up > down)
break;
for(int i = down; i >= up; i--)
res[i][left] = cnt++;
left++;
if(left > right)
break;
}
return res;
}
};