輸出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
