Instead of coding for each direction, I find out it's easier to use an array to indicate which way we're going.

```
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if(n < 1)
return matrix;
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int i = 0, j = -1, num = 1;
for(int count = 0; n > 0; count++){
if((count & 1) == 1) n--;
for(int k = 0; k < n; k++){
i += directions[count % 4][0];
j += directions[count % 4][1];
matrix[i][j] = num++;
}
}
return matrix;
}
```