java之回形矩阵的打印和输出

java之回形矩阵的打印和输出

java之回形矩阵的打印和输出
代码如下:

/**
 * 
 */
package javaLearn;

/**
 * @author Administrator
 *qq:1012885458
 */
public class 回形矩阵的打印 {
    
    
	
	static int length=8;
	static int value=1;
	//二维数组
	static int[][] snake=new int[length][length];
	static Direction lastDirection=Direction.Right;//代表当前 前进的方向;
	static enum Direction{
    
    //枚举
		Right,Down,Left,Up;
	}
	
	//按照顺时针从外到内的填写数字
	public static void initialArray() {
    
    
		int row=0,col=0;
		for(int c=0;c<length*length;c++) {
    
    
			//循环填充数字
			snake[row][col]=value;
			lastDirection=findDirectio(row,col);//寻找方向
			switch(lastDirection){
    
    
			case Right:
				col++;
				break;
			case Down:
				row++;
				break;
			case Left:
				col--;
				break;
			case Up:
				row--;
				break;
			default:
				System.out.println("Error!");
			
			}
			value++;	
		}
	}
	
	//根据当前的方向,求出结合当前位置,确定出下一步的方向;
	static Direction findDirectio(int row ,int col) {
    
    
		Direction direction=lastDirection;
		switch(direction) {
    
    
		case Right:
			//如果在了右边的边界或者右边已经有了数字,则转弯向下;
			if(col==length-1 || snake[row][col+1]!=0) {
    
    
				direction=Direction.Down;	
			}
			break;
		case Down:
			if(row==length-1||snake[row+1][col]!=0) 
				direction=Direction.Left;
			break;
		case Left:
			if(col==0||snake[row][col-1]!=0)
				direction=Direction.Up;
			break;
		case Up:
			if(row==0||snake[row-1][col]!=0)
				direction=Direction.Right;
			break;
		}
		 		
		return direction;}
	
	//打印
	static void print(int[][] arr) {
    
    
		for(int i=0;i<length;i++) {
    
    
			for(int j=0;j<length;j++) {
    
    
				System.out.printf(" %2d",arr[i][j]);
			}
				System.out.println();
		}
	}
	
	//主函数
	public static void main(String args[]) {
    
    
		initialArray();
		print(snake);
	}
	
	

}

猜你喜欢

转载自blog.csdn.net/weixin_42590083/article/details/112206479