class Solution {
private static final int[][] DIRECTIONS = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int i = 0;
int j = 0;
int direction = 0;
for (int cur = 1; cur <= n * n; cur++) {
res[i][j] = cur;
int x = i + DIRECTIONS[direction][0];
int y = j + DIRECTIONS[direction][1];
if (x < 0 || x >= n || y < 0 || y >= n || res[x][y] != 0) {
direction = (direction + 1) % 4;
}
i += DIRECTIONS[direction][0];
j += DIRECTIONS[direction][1];
}
return res;
}
}