打印二维阵列螺旋的次序阵列、次序、螺旋

2023-09-10 23:11:29 作者:笑話如人

我如何打印5×5的二维数组中的螺旋的次序?

How do I print a 5×5 two-dimensional array in spiral order?

有没有什么公式,这样我可以在螺旋的顺序打印任何大小的数组?

Is there any formula so that I can print an array of any size in spiral order?

推荐答案

我们的想法是把矩阵作为一系列的层,右上层和左下层。要打印矩阵螺旋状,我们可以从这些基质剥离层,打印去皮的一部分,递归调用的遗留部分打印。递归终止时,我们没有任何更多的层进行打印

The idea is to treat the matrix as a series of layers, top-right layers and bottom-left layers. To print the matrix spirally we can peel layers from these matrix, print the peeled part and recursively call the print on the left over part. The recursion terminates when we don't have any more layers to print.

输入矩阵:

1 2 3 4 
5 6 7 8
9 0 1 2   
3 4 5 6 
7 8 9 1

脱皮右上方层后:

 1 2 3 4 
       8
5 6 7  2
9 0 1  6   
3 4 5  1 
7 8 9

从子矩阵剥离左下角层后:

   6 7
5  0 1   
9  4 5
3 
7 8 9 

脱皮右上角层从子矩阵后:

    6 7
      1   
   0  5
   4

从子矩阵剥离左下角层后:

  0
  4

递归终止。

C函数:

// function to print the top-right peel of the matrix and 
// recursively call the print bottom-left on the submatrix.
void printTopRight(int a[][COL], int x1, int y1, int x2, int y2) {
    int i = 0, j = 0;

    // print values in the row.
    for(i = x1; i<=x2; i++) {
        printf("%d ", a[y1][i]);
    }

    // print values in the column.
    for(j = y1 + 1; j <= y2; j++)         {
        printf("%d ", a[j][x2]);
    }

    // see if more layers need to be printed.
    if(x2-x1 > 0) {
        // if yes recursively call the function to 
        // print the bottom left of the sub matrix.
        printBottomLeft(a, x1, y1 + 1, x2-1, y2);
    }
}

// function to print the bottom-left peel of the matrix and 
// recursively call the print top-right on the submatrix.
void printBottomLeft(int a[][COL], int x1, int y1, int x2, int y2) {
    int i = 0, j = 0;

    // print the values in the row in reverse order.
    for(i = x2; i>=x1; i--) {
        printf("%d ", a[y2][i]);
    }

    // print the values in the col in reverse order.
    for(j = y2 - 1; j >= y1; j--) {
        printf("%d ", a[j][x1]);
    }

    // see if more layers need to be printed.
    if(x2-x1 > 0) {
        // if yes recursively call the function to 
        // print the top right of the sub matrix.
        printTopRight(a, x1+1, y1, x2, y2-1);
    }
}

void printSpiral(int arr[][COL]) {
    printTopRight(arr,0,0,COL-1,ROW-1);
    printf("\n");
}

Ideone链接