Accepted clear Java Solution


  • 0
    M

    //the basic idea is to control the traverse direction, "left, right, down up" and change the four bounds dynamically.

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result=new ArrayList<>();
        if(matrix.length==0){
            return result;
        }
        char d='r';
        int i=0;
        int j=0;
        int uB=0;
        int rB=matrix[0].length-1;
        int dB=matrix.length-1;
        int lB=0;
        while(!invalid(i,j,uB,rB,dB,lB)){
            result.add(matrix[i][j]);
            if(d=='r'){
                if(j+1>rB){
                    d='d';
                    uB++;
                    i=i+1;
                }
                else{
                    j=j+1;
                }
            }
            else if(d=='d'){
                if(i+1>dB){
                    d='l';
                    rB--;
                    j=j-1;
                }
                else{
                    i=i+1;
                }
            }
            else if(d=='l'){
                if(j-1<lB){
                    d='u';
                    dB--;
                    i=i-1;
                }
                else{
                    j=j-1;
                }
            }
            else{
                if(i-1<uB){
                    d='r';
                    lB++;
                    j=j+1;
                }
                else{
                    i=i-1;
                }
            }
        }
        return result;
    }
    public boolean invalid(int i,int j,int uB,int rB,int dB,int lB){
        if(i>=uB && i<=dB && j>=lB && j<=rB){
            return false;
        }
        else{
            return true;
        }
    }

Log in to reply
 

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