以螺旋顺序打印二维阵列

时间:2011-10-20 18:24:13

标签: java arrays spiral

  

可能重复:
  Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)

如何使用JAVA以螺旋顺序打印二维数组?请帮忙,我不知道。

示例数组:

1  2  3  4

5  6  7  8

9  10 11 12

13 14 15 16

输出:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

这是我试过的:

public static void main(String [] args){

    int[][] values = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};

    for (int i = (values.length * values[0].length)-1, j = 0; i > 0; i--, j++) {
          for (int k = j; k < i; k++) {
              System.out.print(values[j][k]);
          }

          for (int k = j; k < i; k++) {
              System.out.print(values[k][i]);
          }

          for (int k = i; k > j; k--) {
              System.out.print(values[i][k]);
          }

          for (int k = i; k > j; k--) {
              System.out.print(values[k][j]);
          }
    }

}

2 个答案:

答案 0 :(得分:3)

void PrintSpiral(int[][] arr, int size)
{
    for (int l = 0; l < size / 2; l++)
    {
        int min = l;
        int max = size - 1 - l;
        for (int i = min; i < max; i++)
            System.out.print("\t" + arr[i][min].ToString());
        for (int j = min; j < max; j++)
            System.out.print("\t" + arr[max][j].ToString());
        for (int i = max; i > min; i--)
            System.out.print("\t" + arr[i][max].ToString());
        for (int j = max; j > min; j--)
            System.out.print("\t" + arr[min][j].ToString());
    }
    // centre is special case: avoiding printing it 4 times.
    if (size % 2 == 1)
        System.out.print("\t" + arr[size / 2][size / 2].ToString());
}

(免责声明:仅在C#上尝试过)

答案 1 :(得分:1)

这是一些Java解决方案:

public static final int X_SIZE = 4;
public static final int Y_SIZE = 4;

public static void main(String[] args) {
    int[][] array = new int[X_SIZE][Y_SIZE];

    for(int i = 0; i < X_SIZE; i++){
        for (int j = 0; j < Y_SIZE; j++){
            array[i][j] = i * X_SIZE + (j + 1);
            System.out.print(array[i][j] + " ");
        } 
        System.out.println();
    }

    System.out.println("************");
    System.out.println("Spiral");       

    spiralPrint(X_SIZE, Y_SIZE, array);
}

public static void spiralPrint(int xSize, int ySize, int matrix[][]){
    int i,  k = 0, l = 0;
    xSize--;  ySize--;      

    while(k <= xSize && l <= ySize){
        for(i = l; i <= ySize; ++i) {
            System.out.print(matrix[k][i]+ " ");
        }           
        k++;

        for(i = k; i <= xSize; ++i) {
            System.out.print(matrix[i][ySize] + " ");
        }
        ySize--;

        for(i = ySize; i >= l; --i) {
                System.out.print(matrix[xSize][i] + " ");
        }
        xSize--;


        for(i = xSize; i >= k; --i) {
            System.out.print(matrix[i][l] + " ");
        }
        l++;
    }
}