思路:找规律
第一次向右走n步,第二次向下走n-1, 第3次向左走n-1,第4次向上走n-2,第5次向右走n-2……
注意二维数据index i,j和坐标轴x,y不要弄混了
public class Solution {
public int[][] generateMatrix(int n) {
int num[][] = new int[n][n];
if (n == 0)
return num;
int i = 0,j = -1; //模拟当前spiral order指针所在的位置, 第一次向右走后变成[0,0]
int number = 0;
int direction_i[] = {0, 0, -1, 1}; //左右上下
int direction_j[] = {-1, 1, 0, 0};
int direc = -1, count = 0, step = n;
boolean repeated = true; //后面每个step都要走两次, 第一次设为true是因为n步只要走1次
while(step > 0){
//先找方向
if (repeated == false){
if ( (n - step) % 2 == 1){
direc = 3;
}else{
direc = 2;
}
}else{
if ((n - step) % 2 == 1){
direc = 0;
}else{
direc = 1;
}
}
//走step步
count = step;
while(count > 0){
i += direction_i[direc];
j += direction_j[direc];
num[i][j] = ++number;
count --;
}
if (repeated == true){
step --;
repeated = false;
}else{
repeated = true;
}
}
return num;
}
}