博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

生产螺旋二维数组

Posted on 2013-07-26 12:38  钟悍  阅读(288)  评论(0编辑  收藏  举报
public class SpiralArray {

    public static int[][] generateSpiralArray(final int x, final int y) {
        int[][] blanks = new int[x][y];
        int direct = 0;
        int num = 0;
        int posX = 0, posY = -1;
        int widthlen = y;
        int heightlen = x;
        int xTimes = heightlen;
        int yTimes = widthlen;
        while (true) {
            if (num == x * y)
                break;
            num++;
            switch (direct) {
            case 0:
                if (--yTimes == 0) {
                    direct = 1;
                    heightlen--;
                    posY++;
                    xTimes = heightlen;
                    break;
                }
                posY++;
                break;
            case 1:
                if (--xTimes == 0) {
                    direct = 2;
                    widthlen--;
                    posX++;
                    yTimes = widthlen;
                    break;
                }
                posX++;
                break;
            case 2:
                if (--yTimes == 0) {
                    direct = 3;
                    heightlen--;
                    posY--;
                    xTimes = heightlen;
                    break;
                }
                posY--;
                break;
            case 3:
                if (--xTimes == 0) {
                    direct = 0;
                    widthlen--;
                    posX--;
                    yTimes = widthlen;
                    break;
                }
                posX--;
                break;
            }
            blanks[posX][posY] = num;
printArray(blanks, x, y); }
return blanks; } priavte static void printArray(final int[][] array, final int x, final int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.printf("%-5d", blanks[i][j]); }
System.out.println(); }

          try {
              Thread.sleep(100);
          } catch (InterruptedException e) {}

          System.out.println();

    }

    public static void main(String[] args) {
        int x = 5, y = 4;
        int[][] array = generateSpiralArray(x, y);
        printArray(array, x, y);
    }

}