```
public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if(n < 1) return result;
int h = 0, v = 0;
int num = 1;
int i = 0, j = 0;
while(num <= n*n)
{
for(i = h; i < n - h; i++)
result[j][i] = num++;
i--;
for(j = v + 1; j < n - v; j++)
result[j][i] = num++;
j--;
for(i = n - h - 2; i >= h; i--)
result[j][i] = num++;
i++;
for(j = n - v - 2; j >= h + 1; j--)
result[j][i] = num++;
j++;
h = h + 1;
v = v + 1;
}
return result;
}
```

}