日期:2014-05-20 浏览次数:20767 次
/* 1 2 3 4 5 * 14 15 16 17 6 * 13 20 19 18 7 * 12 11 10 9 8 4X5螺旋数组 */ public class Helix { public static void main(String[] args) { int n = 4; int m = 5; int [][] data = new int[n][m]; final int UP = 0; final int DOWN = 1; final int LEFT = 2; final int RIGHT = 3; int dire = RIGHT; // 当前数字的移动方向 int value = 1; // 数组元素的值 int row = 0; // 行下标 int col = 0; // 列下标 data[0][0] = 1; while (value < n*m) { switch(dire) { case RIGHT: col++; //移动到后一列 if (col >= m) { col--; dire = DOWN; continue; }else if(data[row][col] != 0) { // 已赋值 col--; dire = DOWN; continue; } break; case DOWN: row++; if (row >= n) { row--; dire = LEFT; continue; } else if(data[row][col] != 0) { row--; dire = LEFT; continue; } break; case LEFT: col--; if (col < 0) { col++; dire = UP; continue; }else if(data[row][col] != 0) { col--; dire = UP; continue; } break; case UP: row--; if (data[row][col] != 0) { row++; dire = RIGHT; continue; } break; } value++; //数值增加1 data[row][col] = value;//赋值 } for(int i = 0;i < data.length;i++){ for(int j = 0;j < data[i].length;j++){ if(data[i][j] < 10){//右对齐 System.out.print(' '); } System.out.print(data[i][j]); System.out.print(' '); } System.out.println(); } } }