思路:设置好转折条件
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list=new ArrayList<>();
int row=matrix.length;//行
int col=matrix[0].length;//列
//int[][] visit=new int[row][col];//初始值为0
boolean[][] visit=new boolean[row][col];
int len=row*col;
int x=0;
int y=0;
while(true){
if(list.size()==len) break;
while(y<col&&!visit[x][y]&&list.size()<len){
list.add(matrix[x][y]);
visit[x][y]=true;
y++;
}
y--;
x++;
while(x<row&&!visit[x][y]&&list.size()<len){
list.add(matrix[x][y]);
visit[x][y]=true;
x++;
}
x--;
y--;
while(y>=0&&!visit[x][y]&&list.size()<len){
list.add(matrix[x][y]);
visit[x][y]=true;
y--;
}
y++;
x--;
while(x>=0 && !visit[x][y] && list.size()<len){
list.add(matrix[x][y]);
visit[x][y]=true;
x--;
}
x++;
y++;
}
return list;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int len=n*n;
int num=1;
boolean[][] visit=new boolean[n][n];
int[][] res=new int[n][n];
int x=0;//行
int y=0;//列
while(true){
if(num>len) break;
while(y<n && !visit[x][y] && num<=len){
res[x][y]=num;//0 3
visit[x][y]=true;
++num;
++y;
}
--y;
++x;
while(x<n && !visit[x][y] && num<=len){
res[x][y]=num;//0 3
visit[x][y]=true;
++num;
++x;
}
--x;
--y;
while(y>=0 && !visit[x][y] && num<=len){
res[x][y]=num;//0 3
visit[x][y]=true;
++num;
--y;
}
++y;
--x;
while(x>=0 && !visit[x][y] && num<=len){
res[x][y]=num;//0 3
visit[x][y]=true;
++num;
--x;
}
++x;
++y;
}
return res;
}
}