public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length ==0){
            return new ArrayList<Integer>();
        }
        int row = matrix.length;
        int col = matrix[0].length;
        
        ArrayList<Integer> result = new ArrayList<Integer>();
        int start = 0;
        while(row > 2 * start && col > 2 * start ){
            print(matrix,result,start,row,col);
            start ++;
        }
        return result;
        
    }
    private void print(int[][] matrix, ArrayList<Integer> result,int start,int row,int col){
        int startX = start;
        int startY = start;
        int endX = col - 1 - start;
        int endY = row - 1 - start;
        //从左到右
        for(int i = startX;i<= endX;i++){
            result.add(matrix[startY][i]);
        }
        //从上到下
        if(startY< endY){
            for(int i = startY+1;i<=endY;i++){
                result.add(matrix[i][endX]);
            }
        }
        //从右到左
        if(endX > startX && startY < endY){
            for(int i = endX- 1 ;i>=startX;i--){
                result.add(matrix[endY][i]);
            }
        }
        //从上到下
        if(startY  < endY - 1 && startX < endX){
            for(int i = endY - 1;i>=startY +1;i--){
                result.add(matrix[i][startX]);
            }
        }
        
        
    }
}