public class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][];
for (int i = 0; i < n; i++){
ans[i] = new int[n];
for (int j = 0; j < n; j++){
ans[i][j] = 0;
}
}
int x = 0;
int y = 0;
boolean right = true;
boolean down = false;
boolean up = false;
boolean left = false;
for (int count = 1; count <= n * n; count++){
ans[x][y] = count;
boolean rightblock = y + 1 >= n || ans[x][y+1] > 0;
boolean leftblock = y - 1 < 0 || ans[x][y-1] > 0;
boolean upblock = x - 1 < 0 || ans[x-1][y] > 0;
boolean downblock = x + 1 >= n || ans[x+1][y] > 0;
if(rightblock && leftblock && upblock){
right = up = left = false;
down = true;
}
else if(rightblock && leftblock && downblock){
right = down = left = false;
up = true;
}
else if(rightblock && downblock && upblock){
right = down = up = false;
left = true;
}
else if(leftblock && downblock && upblock){
left = down = up = false;
right = true;
}
if(left){
y--;
}
else if(right){
y++;
}
else if(down){
x++;
}
else if(up){
x--;
}
}
return ans;
}
}