class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int x = 0, y = 0;
int d = 0;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; //这里可以用dx[] = {0, 1, 0, -1}
vector<vector<int>> matrix(n, vector<int>(n));
for (int i = 0; i < n * n; i ++) { // int i = 1; i <= n * n; i ++
matrix[x][y] = i + 1; // matrix[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || matrix[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return matrix;
}
};