回型矩阵(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

转载于:https://www.cnblogs.com/vovo/p/5628973.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值