My simple iterative Java solution with explanation


  • -1
    Z
     public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> record=new ArrayList<Integer>();
        if(matrix.length==0)return record;
        int m=matrix.length;
        int n=matrix[0].length;
        int col=n;
        int lrow=0;
        int row=m;
        int lcol=0;
        int count=0;
        while(true){
            for(int i=lcol;i<col;i++){
                record.add(matrix[lrow][i]);
                count++;
                if(count==m*n)return record;
            }
            lrow++;
            for(int i=lrow;i<row;i++){
                record.add(matrix[i][col-1]);
                count++;
                if(count==m*n)return record;
            }
            col--;
            for(int i=col-1;i>=lcol;i--){
                record.add(matrix[row-1][i]);
                count++;
                if(count==m*n)return record;
            }
            row--;
            for(int i=row-1;i>=lrow;i--){
                record.add(matrix[i][lcol]);
                count++;
                if(count==m*n)return record;
            }
            lcol++;
            
        }
        
    }
    

    I use four inner loops to do the four directions' move steps.And use lcol,col, lrow and row four variables as the move bounds.
    For example, the first inner loop does the "right" move. But the move must be limited between "lcol"(the left column bound) and "col"(the right column bounds). Then after "right" move touches the right column bound, we turn the move to "down". But before move downward, the lrow(the upper row bound) should plus one because we've already walked through the first line and should never go through it again.

    At last, I set a counter to count how many steps have been through. If the counter equals the number of elements in matrix, the list should be returned.


Log in to reply
 

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