Simple java solution with comments


  • 0
    public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> l=new ArrayList<>();
            if(matrix.length==0) return l;
            int i=0,j=0,m=matrix.length,n=matrix[0].length,d=1;//d represents direction with 4 options
            int mUp=1,mDown=m-1,nLeft=0,nRight=n-1;//set bounds(pay attention that up bound of row is 1 at the beginning, since when the pointer goes up to the bound first time, it should not reach a[0][0].
            for(int k=0;k<m*n;k++){//k is the counter to make sure exactly m*n number is added
                l.add(matrix[i][j]);
                if(d==1){//go right
                    if(j<nRight) j++;
                    else {
                        d=2;
                        nRight--;
                        i++;
                    }
                }else if(d==2){//go down
                    if(i<mDown) i++;
                    else {
                        d=3;
                        mDown--;
                        j--;
                    }
                }else if(d==3){//go left
                    if(j>nLeft) j--;
                    else {
                        d=4;
                        nLeft++;
                        i--;
                    }
                }else if(d==4){//go up
                    if(i>mUp) i--;
                    else {
                        d=1;
                        mUp++;
                        j++;
                    }
                }
            }
            return l;
        }
    

Log in to reply
 

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