2d Array in Spiral Order

后端 未结 6 881
失恋的感觉
失恋的感觉 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 01:01

    Below function is a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.

    int[][] spiralNumbers(int n) {
    int[][] matrix = new int[n][n];
    for (int step = 0, a = 0, size; step < n/2; step++) {
        size = (n - step * 2 - 1);
        for (int i = 0, chunk, chunkIndex, chunkOffset; i < 4 * size; i++) {
            chunk = i / size;
            chunkIndex = i % size;
            chunkOffset = n - step - 1;
            switch (chunk) {
                case 0:
                    matrix[step][chunkIndex + step] = a+1;
                    break;
                case 1:
                    matrix[chunkIndex + step][chunkOffset] = a+1;
                    break;
                case 2:
                    matrix[chunkOffset][chunkOffset - chunkIndex] = a+1;
                    break;
                case 3:
                    matrix[chunkOffset - chunkIndex][step] = a+1;
                    break;
                default:
                    throw new IndexOutOfBoundsException();
            }
            a++;
        }
        if (n % 2 == 1) {
            matrix[n/2][n/2] = n * n;
        }
    }
    return matrix; 
    }
    

提交回复
热议问题