在命令行输入一个自然数N,实现螺旋排列
public class Test { public static void main(String[] args) { /* String inputNum = "3"; if ("3".equals(inputNum)) { System.out.println("01 02 03"); System.out.println("08 09 04"); System.out.println("07 06 05"); } if ("6".equals(inputNum)) { System.out.println("01 02 03 04 05 06"); System.out.println("20 21 22 23 24 07"); System.out.println("19 32 33 34 25 08"); System.out.println("18 31 36 35 26 09"); System.out.println("17 30 29 28 27 10"); System.out.println("16 15 14 13 12 11"); }*/ final int INPUT_NUMBER = 6; //0=右 1=下 2=左 3=上 int direction = 0; int directionCount=0; int xLine = 0; int yLine = 0; int[][] intArray = new int[INPUT_NUMBER][INPUT_NUMBER]; //初始化 for (int x = 0; x < INPUT_NUMBER; x++) { for (int y = 0; y < INPUT_NUMBER; y++) { intArray[x][y] = 0; } } for (int x = 1; x <= INPUT_NUMBER * INPUT_NUMBER; x++) { switch (direction) { case 0: if (yLine + 1 >= INPUT_NUMBER || (directionCount>=3 && intArray[xLine][yLine+1] != 0)) { direction = ++direction % 4; directionCount++; intArray[xLine][yLine] = x; xLine++; } else { intArray[xLine][yLine] = x; yLine++; } break; case 1: if (xLine + 1 >= INPUT_NUMBER || (directionCount>=3 && intArray[xLine+1][yLine] > 0)) { direction = ++direction % 4; directionCount++; intArray[xLine][yLine] = x; yLine--; } else { intArray[xLine][yLine] = x; xLine++; } break; case 2: if (yLine == 0 || (directionCount>=3 && intArray[xLine][yLine-1] > 0)) { direction = ++direction % 4; directionCount++; intArray[xLine][yLine] = x; xLine--; } else { intArray[xLine][yLine] = x; yLine--; } break; case 3: if (xLine== 0 || (directionCount>=3 && intArray[xLine-1][yLine] > 0)) { direction = ++direction % 4; directionCount++; intArray[xLine][yLine] = x; yLine++; } else { intArray[xLine][yLine] = x; xLine--; } break; } } //打印 System.out.println("***********************"); for (int a = 0; a < INPUT_NUMBER; a++) { for (int b = 0; b < INPUT_NUMBER; b++) { System.out.print(" " + Test.padRight(String.valueOf(intArray[a][b]),5,'0')); } System.out.println(" "); } } /** * String右对齐 * 前补位 * @author */ public static String padRight(String src, int len, char ch) { int diff = len - src.length(); if (diff <= 0) { return src; } char[] charr = new char[len]; System.arraycopy(src.toCharArray(), 0, charr, diff, src.length()); for (int i = 0; i < diff; i++) { charr[i] = ch; } return new String(charr); } }