54. Spiral Matrix

Link

Solution

依照順序訪問,另外將 special case (長矩陣,寬矩陣)放在迴圈外面另外處理

  public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ret = new LinkedList<>();
        
        int m = matrix.length;
        if(m == 0) return ret;
        int n = matrix[0].length;
        
        
        int colStart = 0, rowStart = 0;
        int colEnd = n-1, rowEnd = m-1;
        
        while(colStart <= colEnd && rowStart <= rowEnd){
            
            for(int i = colStart; i <= colEnd; i++){
                ret.add(matrix[rowStart][i]);
            }
            rowStart++;

            for(int i = rowStart; i <= rowEnd; i++){
                ret.add(matrix[i][colEnd]);
            }
            colEnd--;
 
            //Avoid previous two operation makes the while condition changes
            if(rowEnd >= rowStart){
                for(int i = colEnd; i >= colStart; i--){
                    ret.add(matrix[rowEnd][i]);
                }
                rowEnd--;
            }
            
            if(colEnd >= colStart){
                for(int i = rowEnd; i >= rowStart; i--){
                    ret.add(matrix[i][colStart]);
                }
                colStart++;
            }
        }
        
        return ret;
    }

Last updated

Was this helpful?