```
public int[][] generateMatrix(int n) {
if (n < 0) return null;
int[][] m = new int[n][n];
int[][] dr = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int indD = 0;
int i=0, j=0;
for (int k=1; k<=n*n; ++k) {
m[i][j] = k;
int nextI = i + dr[indD][0], nextJ = j + dr[indD][1];
if (nextI < 0 || nextI >= n || nextJ < 0 || nextJ >= n || m[nextI][nextJ] != 0) {
indD = (indD + 1) % 4;
i = i + dr[indD][0];
j = j + dr[indD][1];
} else {
i = nextI;
j = nextJ;
}
}
return m;
}
```