图解:输入任意一个数值,打印一个螺旋矩阵(二维数组)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41548307/article/details/83387918

更多算法题请看本人博客分类--算法 

public class Demo11 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		while(true){
			
			int n = sc.nextInt();
			if(n == -1){
				break;
			}
			
			//创建n行 n列的二维数组
			int[][] arr = new int[n][n];
			//初始化坐标
			int i =0;
			int j =0;
			//初始化方向
			/*
			 * 0:从左至右
			 * 1: 从上至下
			 * 2:从右至左
			 * 3:从下至上
			 * */
			int direction = 0;
			
			arr[i][j] = 1;
			//赋值的整个过程
			for(int step = 2;step<=n*n;step++){
				
				if(direction ==0){
					//向右赋值  i不变,j+1
					//已经到了右边界 或者 右边的值已经赋过了
					if((j == n-1)||arr[i][j+1]!=0){
						
						//不允许赋值的,改变赋值的方向
						direction = 1;
						//因为没有赋值成功,不允许step加
						step --;
						
					}else{
						//可以赋值
						j++;
						arr[i][j] = step;
					}
					continue;
				}
				//从上至下
				if(direction ==1){
					
					//向下赋值 i+1,j不变
					if(i == n-1 || arr[i+1][j]!=0){
						direction = 2;
						step--;
					}else{
						
						i++;
						arr[i][j] = step;
					}
					continue;
				}
				//从右至左
				if(direction ==2){
					//向左赋值 i不变,j-1
					if(j==0 || arr[i][j-1] !=0){
						direction = 3;
						step--;
					}else{
						j--;
						arr[i][j]=step;
					}
					continue;
				}
				//从下至上
				if(direction == 3){
					//向上赋值 i-1,j 不变
					if(i ==0 || arr[i-1][j] !=0){
						direction = 0;
						step--;
					}else{
						i--;
						arr[i][j] = step;
					}
					continue;
				}
			}
			
			for(i = 0;i<n;i++){
				
				for(j =0;j<n;j++){
					System.out.print(arr[i][j]+"\t");
				}
				System.out.println("");
			}
			
		}
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41548307/article/details/83387918