题意
输出旋转矩阵
题解
和54题类似,通过不断缩小矩阵边界来解决。由于此时是n阶方阵,所以此时左上角和右下角其实可以用(x,x)和(n,n)表示。
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int x = 0, y = 0;
vector<vector<int> > mat(n, vector<int>(n,0));
n--;
int cnt = 1;
while(x <= n)
{
for(int j = y; j <= n; j++)
mat[x][j] = cnt++;
for(int i = x + 1; i <= n; i++)
mat[i][n] = cnt++;
for(int j = n - 1; j >= y; j--)
mat[n][j] = cnt++;
for(int i = n - 1; i > x; i--)
mat[i][y] = cnt++;
x++,y++,n--;
}
return mat;
}
};