以螺旋顺序打印二维数组

以螺旋顺序打印二维数组

本文介绍了以螺旋顺序打印二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以螺旋顺序打印一个 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");
}

这篇关于以螺旋顺序打印二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:51