Leetcode54螺旋矩阵

代码:

class Solution {
    public List spiralOrder(int[][] matrix) {
        List res = new ArrayList<>();
        if(matrix==null||matrix.length==0||matrix[0].length==0)return res;
        int left=0,right=matrix[0].length-1,up=0,down = matrix.length-1;
        while(left<=right&&up<=down){
            for(int i=left;i<=right;i++){
                res.add(matrix[up][i]);
            }
            for(int i=up+1;i<=down;i++){
                res.add(matrix[i][right]);
            }
            for(int i=right-1;i>=left&&up!=down;i--){
                res.add(matrix[down][i]);
            }
            for(int i=down-1;i>up&&left!=right;i--){
                res.add(matrix[i][left]);
            }
            left++;
            right--;
            up++;
            down--;
        }
        return res;
    }
}

你可能感兴趣的:(矩阵,算法,leetcode)