class Solution {
public int[][] generateMatrix(int n) {
int[][] s = new int[n][n];
int x = 0;
int y = 0;
int max = n - 1;
boolean xt = true;
boolean yt = true;
for(int i = 1;i <= n*n;i++){
s[y][x] = i;
if(xt != yt){
if(yt){
y++;
if(y >= max || s[y+1][x] != 0){
yt = !yt;
}
}else{
y--;
if(y <= 0||s[y-1][x] != 0){
yt = !yt;
}
}
}else{
if(xt){
x++;
if(x >= max || s[y][x+1] != 0){
xt = !xt;
}
}else{
x--;
if(x <= 0||s[y][x-1] != 0){
xt = !xt;
}
}
}
}
return s;
}
}