碰到边界调转方向即可
class Solution {
public int[] printMatrix(int[][] matrix) {
if(matrix.length==0) return new int[0];
int m=matrix.length;
int n=matrix[0].length;
int res[]=new int[m*n];
boolean vis[][]=new boolean[m+1][n+1];
List<Integer>list=new ArrayList<>();
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
int a=0,b=0,d=1;
for(int i=0;i<m*n;i++){
list.add(matrix[a][b]);
vis[a][b]=true;
int x=a+dx[d],y=b+dy[d];
if(x<0||x==m||y<0||y==n|vis[x][y]){
d=(d+1)%4;
x=a+dx[d];
y=b+dy[d];
}
a=x;
b=y;
}
for(int i=0;i<m*n;i++){
res[i]=list.get(i);
}
return res;
}
}