2d Array in Spiral Order

后端 未结 6 884
失恋的感觉
失恋的感觉 2020-12-20 00:30

I\'m trying to fill an array in spiral order. So far, I can print the array in spiral order, but is there a way to modify the array so that i can fill it in spiral order and

6条回答
  •  情深已故
    2020-12-20 00:52

    int maxValue = target.length * target[0].length;
    
    private int[][] generateMatrix(int[][] target, int level, int currentVal) {
        // always start from lower left corner in each layer
        int w = level;
        int h = target.length - level - 1;
    
        // fill the bottom line
        int i = 0;
        for (i = w; i < target[0].length - level && currentVal <= maxValue; i++) {
            target[h][i] = currentVal++;
        }
    
        w = target[0].length - level - 1;
    
        int j = 0;
        // fill the right line
        for (j = h - 1; j >= level && currentVal <= maxValue; j--) {
            target[j][w] = currentVal++;
        }
    
        h = level;
    
        // fill the above line
        for (i = w - 1; i >= level && currentVal <= maxValue; i--) {
            target[h][i] = currentVal++;
        }
        w = level;
    
        // fill the left line
        for (j = h + 1; j < target.length - level - 1 && currentVal <= maxValue; j++) {
            target[j][w] = currentVal++;
        }
    
        if (currentVal > maxValue)
            return target;
        return generateMatrix(target, ++level, currentVal);
    
    }
    

提交回复
热议问题