Clear Java solution,23 lines


  • 0
    P
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans=new ArrayList<>();
        if(matrix.length==0) return ans;
        int a=matrix[0].length,b=matrix.length-1;
        int p=0,q=0;
        while(true){
            if(a<=0) break;
            for(int i=0;i<a;i++) ans.add(matrix[p][q++]);
            q--;p++;
            if(b<=0) break;
            for(int i=0;i<b;i++) ans.add(matrix[p++][q]);
            p--;q--;
            if(a-1<=0) break;
            for(int i=0;i<a-1;i++) ans.add(matrix[p][q--]);
            q++;p--;
            if(b-1<=0) break;
            for(int i=0;i<b-1;i++) ans.add(matrix[p--][q]);
            p++;q++;
            a-=2;
            b-=2;
        }
        return ans;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.