import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix int整型二维数组
     * @return int整型ArrayList
     */
    public ArrayList<Integer> spiralOrder (int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new ArrayList<>();
        }
        int n = matrix.length;
        int m = matrix[0].length;
        ArrayList<Integer> list = new ArrayList<>();
        int count = 0;
        int x = 0;
        int y = 0;
        int left = 0;
        int right = m - 1;
        int top = 0;
        int bottom = n - 1;
        //方向
        int forword = 0;

        while (count < n * m) {
            count++;
            //往右走
            if (forword % 4 == 0) {
                if (y <= right) {
                    list.add(matrix[x][y]);
                    if (y == right) {
                        forword++;
                        top++;
                        x++;
                    } else {
                        y++;
                    }

                }
            } else if (forword % 4 == 1) {
                if (x <= bottom) {
                    list.add(matrix[x][y]);
                    if (x == bottom) {
                        right--;
                        forword++;
                        y--;
                    } else {
                        x++;
                    }
                }
            } else if (forword % 4 == 2) {
                if (y >= left) {
                    list.add(matrix[x][y]);
                    if (y == left) {
                        bottom--;
                        forword++;
                        x--;
                    } else {
                        y--;
                    }
                }
            } else if (forword % 4 == 3) {
                if (x >= top) {
                    list.add(matrix[x][y]);
                    if (x == top) {
                        left++;
                        forword++;
                        y++;
                    } else {
                        x--;
                    }
                }
            }
        }
        return list;
    }
}