import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ans = new ArrayList<>();
int top,bottom,right,left,i;
if(matrix.length==0)return ans;
top = 0;
bottom = matrix.length-1;
left = 0;
right = matrix[0].length - 1;
while(top< (matrix.length+1)/2&&left< (matrix[0].length+1)/2){
for(i=left;i<=right;i++)ans.add(matrix[top][i]);
for(i=top+1;i<=bottom;i++)ans.add(matrix[i][right]);
for(i=right-1;top!=bottom&&i>=left;i--)ans.add(matrix[bottom][i]);
for(i=bottom-1;right!=left&&i>=top+1;i--)ans.add(matrix[i][left]);
top++;
bottom--;
right--;
left++;
}
return ans;
}
}