Concise solution in Java

  • 9

    After each iteration the scope of each for loop is reduced. The if condition before the two last loops is to avoid duplicates.

     public List<Integer> spiralOrder(int[][] mtx) {
        List<Integer> ret=new LinkedList<>();
        if(mtx.length==0)return ret;
        int m=mtx.length;
        int n=mtx[0].length;
        int min=Math.min(m,n);
        for(int b=0;b<Math.ceil(min/2.);b++){
            for(int a=b;a<n-b;a++)ret.add(mtx[b][a]);
            for(int a=b+1;a<m-b;a++)ret.add(mtx[a][n-b-1]);
            if(b!=m-b-1)for(int a=n-b-2;a>=b;a--)ret.add(mtx[m-b-1][a]);
            if(n-b-1!=b)for(int a=m-b-2;a>b;a--)ret.add(mtx[a][b]);
        return ret;

Log in to reply

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