class Solution {
static int[] dx = {-1, 0, 1,0};//上右下左
static int[] dy = {0,1,0,-1};
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int total = n * n;
int x = 0,y = 0, d= 1;//先一直往右走
for(int i = 1;i <= total;i++){
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || res[a] != 0) {//遇到边界反转方向
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
}