Java 0ms solution, simple, clear, easy


  • 0
    R
    public List<Integer> spiralOrder(int[][] matrix) {
        if(matrix==null || matrix.length==0||matrix[0].length==0){
            return new ArrayList<>();
        }
        int startX=0, startY=0, endX=matrix[0].length-1, endY=matrix.length-1;
        List<Integer> result = new ArrayList<>();
        while(true){
            for(int index=startX; index<=endX; index++){
                result.add(matrix[startY][index]);
            }
            startY++;
            if(startY>endY) break;
            
            for(int index=startY; index<=endY; index++){
                result.add(matrix[index][endX]);
            }
            endX--;
            if(endX<startX) break;
            
            for(int index=endX; index>=startX; index--){
                result.add(matrix[endY][index]);
            }
            endY--;
            if(startY>endY) break;
            
            for(int index=endY; index>=startY; index--){
                result.add(matrix[index][startX]);
            }
            startX++;
            if(startX>endX) break;
        }
        return result;
    }

Log in to reply
 

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