设置边界,left,right,top,bottom,有效的条件是left<=right,top<=bottom.

每完成一行后,需要修改边界,然后再比较,so,++left;

    /**
     * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
     * @param matrix  矩阵
     * @return  顺时针的顺序依次打印出每一个数字
     */
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res=new ArrayList<>();
        if(matrix==null||matrix.length==0){
            return res;
        }
        int top=0,bottom=matrix.length-1,left=0,right=matrix[0].length-1;
        while (true){
            for(int i=left;i<=right;i++){
                res.add(matrix[top][i]);
            }
            if(++top>bottom){
                break;
            }
            for(int i=top;i<=bottom;i++){
                res.add(matrix[i][right]);
            }
            if(left>--right){
                break;
            }
            for(int i=right;i>=left;i--){
                res.add(matrix[bottom][i]);
            }
            if(top>--bottom){
                break;
            }
            for(int i=bottom;i>=top;i--){
                res.add(matrix[i][left]);
            }
            if(++left>right){
                break;
            }

        }

        return res;
    }

大佬的图解:来源:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/
图片说明