回型矩阵(java)
输出3阶回型矩阵,
1 2 3
8 9 4
7 6 5
现在要实现8阶:
程序如下
public class Test { private static int length = 8; private static int value = 1; //方向 public enum Direction{ Left,Right,Up,Down; } private Direction lastDirection = Direction.Right; public static void main(String[] args) { new Test().initMatrix(); } public void initMatrix(){ int row = 0; int col = 0; //初始化 int[][] matrix = new int[length][length]; for(int i=0;i<length*length;i++){ //赋值 matrix[row][col] = value; //根据所在的行列,判断下一步的走向 Direction nowDirection = getDirection(row,col); switch(nowDirection){ case Left: col--; break; case Right: col++; break; case Up: row--; break; case Down: row++; break; } value++; } for(int i=0;i<length;i++){ for(int j=0;j<length;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(""); } } //这里最为重要 //向左走时,是在回型的最下面,根据所在行号判断到哪列就转向上.比如row=6,那么col=1时就可以转向了. //向右走时,是在回型的最上面,根据所在行号判断到哪列就转向下.比如row=0,那么col=7时就可以转向了. //向下走时,是在回型的最右面,根据所在列号判断到哪行就转向左.比如col=6,那么row=6时就可以转向了. //向上走时,是在回型的最左面,根据所在列号判断到哪行就转向右.比如col=0,那么row=1时就可以转向了. public Direction getDirection(int row,int col){ switch(lastDirection){ case Left: if(col==(length-1-row)) lastDirection = Direction.Up; break; case Right: if(col==(length-1-row)) lastDirection = Direction.Down; break; case Up: if(row==(col+1)){ lastDirection = Direction.Right; } break; case Down: if(row==col) lastDirection = Direction.Left; break; } return lastDirection; } }
输出:
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15