java实现螺旋矩阵

import java.util.Scanner;
/**
* @文件名称 :CycleMatrix.java
* @功能描述 :
*java实现螺旋矩阵
* @创建者 :云守护    542335496@qq.com
 */
public class SpiralMatrix {	
	static int length;
	static int[][] snake;
	static int value=1;
	static enum Direction{
		Right,Down,Left,Up;
	}
	public static void main(String[] args) {
	
		for(int k=0;k<10;k++){
			exe();
		}
	}
	public  static void exe(){
		Scanner input=new Scanner(System.in);
		//System.out.println("input number:");
		length=Integer.parseInt(input.nextLine());
		snake=new int[length][length];
		initArray();
		for(int i=0;i<length ;i++){
			
			for(int j=0;j<length ;j++){
				System.out.print(snake[i][j]+"\t");
			}
			System.out.println();
		}
	}
	public static void initArray() {
		int row=0;
		int line=0;
		Direction direction=Direction.Right;
		for(int i=0;i<length*length;i++){
			
			snake[row][line]=value;
			direction=getDirection(row,line,direction);
			switch (direction) {
			case Right:
				line++;
				break;
			case Down:
				row++;
				break;
			case Left:
				line--;
				break;
			case Up:
				row--;
				break;
			}
			value++;
		}
	}
	private static Direction getDirection(int row, int line, Direction direction) {
		Direction nextDirection=direction;
		if(direction==Direction.Right){
			if(line==length-1|| snake[row][line+1]!=0){
				nextDirection=Direction.Down;
			}
		}else if(direction==Direction.Down){
			if(row==length-1|| snake[row+1][line]!=0){
				nextDirection=Direction.Left;
			}
		}else if(direction==Direction.Left){
			if(line==0|| snake[row][line-1]!=0){
				nextDirection=Direction.Up;
			}
		}else if(direction==Direction.Up){
			if(snake[row-1][line]!=0){
				nextDirection=Direction.Right;
			}
		}	
		return nextDirection;
	}
	

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值