An accepted java solution


  • 0
    N
    public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> list = new ArrayList<Integer>();
            if(matrix == null || matrix.length ==0) return list;
            
            int rows = matrix.length;
            int cols = matrix[0].length;
            
            int loops = Math.min(rows,cols)/2;
            int lop = 0;
            
            rows--;
            cols--;
            
            while(lop < loops ){
                int i = lop;
                int j = lop;
                for(;j<=cols-1-lop;j++){
                    list.add(matrix[i][j]);
                }
                for(;i<=rows-1-lop;i++){
                    list.add(matrix[i][j]);
                }
                for(;j>=lop+1;j--){
                    list.add(matrix[i][j]);
                }
                for(;i>=lop+1;i--){
                    list.add(matrix[i][j]);
                }
                
                lop++;
            }
            
            if((rows&1) == 0 && (cols &1) == 0 && rows == cols){ // both odd
                list.add(matrix[loops][loops]);
            }else if((cols &1) == 0 && cols<rows){// cols is odd
                for(int i=lop;i<rows-lop+1;i++){
                    list.add(matrix[i][loops]);
                }
            }else if((rows&1) == 0 && cols>rows){// rows is odd
                for(int j=lop;j<cols-lop+1;j++){
                    list.add(matrix[loops][j]);
                }
            }
            
            return list;
        }

Log in to reply
 

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