import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
if(matrix.length == 0)return new ArrayList<Integer>();
int[] ax= new int[]{0,1, 0,-1};
int[] ay= new int[]{1,0,-1,0};
int turn = 0,i = 0,j = -1;//turn表示方向 0右 1下 2左 3上
int n=matrix.length, m=matrix[0].length, count = n*m;
int[][] visit = new int[n][m];//访问数组
ArrayList<Integer> ans = new ArrayList<>();
while(count>0){
boolean flag = true;
while(flag){
if(i+ax[turn] < n && i+ax[turn] >= 0 && j+ay[turn] < m && j+ay[turn] >= 0 && visit[i+ax[turn]][j+ay[turn]] == 0){
i = i+ax[turn];
j = j+ay[turn];
flag = false;
} else turn = (turn+1)%4;
}//循环找方向
ans.add(matrix[i][j]);
visit[i][j] = 1;
count--;
}
return ans;
}
}