59. Spiral Matrix II

Link

Solution

這題做法是設定區間(colStart, colEnd, rowStart, rowEnd),然後按照右,下,左,上的方式反覆填值。

每次填完一個方向之後,將區間進行對應的更新。

直到最後區間已經完全密合為止

   public int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];

        int value = 1;
        int rowStart = 0, rowEnd = n-1;
        int colStart = 0, colEnd = n-1;
        while(rowStart <= rowEnd && colStart <= colEnd){
            for(int i = colStart; i <= colEnd; i++){
                ret[rowStart][i] = value++;
            }
            rowStart++;
            for(int i = rowStart; i <= rowEnd; i++){
                ret[i][colEnd] = value++;
            }
            colEnd--;
            for(int i = colEnd; i >= colStart; i--){
                ret[rowEnd][i] = value++;
            }
            rowEnd--;
            
            for(int i = rowEnd; i >= rowStart; i--){
                ret[i][colStart] = value++;    
            }
            colStart++;
            
        }
        
        return ret;
    }

Last updated

Was this helpful?