My solution idea is from the Rotate Image problem.


  • 0
    S
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result=new ArrayList<Integer>();
        int m=matrix.length;
        if(m==0) return result;
        int n=matrix[0].length;
        int layer=(Math.min(m,n)==1)?1:Math.min(m,n)-1; // number of layers.
        for(int i=0;i<layer;i++){
            int offset1=n-1-2*i;//the offset in row.
            int offset2=m-1-2*i;// the offset in column..
            if(offset1==0){ // only one row left, just add all elements left to result.
                for(int j=0;j<=offset2;j++){
                        result.add(matrix[i+j][i]);
                }
                break;
            }
            
            if(offset2==0){ // only one column left, just add all elements left to result
               for(int j=0;j<=offset1;j++){
                       result.add(matrix[i][i+j]);
               } 
               break;
            }
            
            for(int j=0;j<offset1;j++){ //peel the top row except the last element from matrix to the result 
                result.add(matrix[0+i][0+i+j]);
            }
            for(int j=0;j<offset2;j++){
                result.add(matrix[0+i+j][n-1-i]); //peel the right column
            }
            for(int j=0;j<offset1;j++){
                result.add(matrix[m-1-i][n-1-i-j]);//peel the bottom row
            }
            for(int j=0;j<offset2;j++){
                result.add(matrix[m-1-i-j][i]); //peel the left column
            }
        }
        return result;
    }

Log in to reply
 

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