螺旋矩阵问题求解

 输入一个矩阵的行列数量,生成一个螺旋矩阵,比如输入5,则打印:
   1       2      3     4     5
   12    13    14   15    6
   11     10    9     8     7
输入3,则打印:
   1        2        3
   8        9        4
   7        6        5

下面就是他的算法

package com.huawei2;

import java.util.Scanner;

public class Test {
	private static int length;
	private Test(){
		  Scanner sc=new Scanner(System.in);
	       System.out.println("请输入一个正整数:");
	       length=sc.nextInt();
	       array =new int[length][length];
	       System.out.println(length);
	       value=1;
	}
	private static int value=0;
	 private static int[][] array=null;
	private static Direction lastDirection=Direction.Right;
	
	static enum Direction{
		Right,Down,Left,Up;
	}
	public static void initArray(){
		int row = 0,line=0;
		
		for(int i=0;i<length*length;i++)
		{
			array[row][line]=value;
			lastDirection=lastDirection(row,line);
			switch(lastDirection)
			{
				case Right:
				{
					line++;
					break;
				}
				case Down:
				{
					row++;
					break;
				}
				case Left:
				{
					line--;
					break;
				}
				case Up:
				{
					row--;
					break;
				}
			}
			value+=1;
		}
	}
	public static Direction lastDirection(int row,int line)
	{
		Direction direction=lastDirection;
		switch(direction){
			case Right:
			{
				if(line==length-1||array[row][line+1]!=0)
					direction=direction.Down;
					break;
			}
			case Down:
			{
				if(row==length-1||array[row+1][line]!=0)
				{
					direction=direction.Left;
					
				}
				break;
			}
			case Left:
			{
				if(line==0||array[row][line-1]!=0)
				{
					direction=direction.Up;
				
				}
				break;
			}
			case Up:
			{
				if(array[row-1][line]!=0)
				{
					direction=direction.Right;
				}
				break;
			}
							
		}
		return direction;
	}
	public static void main(String[] args) {
		Test test=new Test();
		test.initArray();
		// show
		for(int i1 = 0; i1 < length; i1++)
		{
			for(int j1 = 0; j1 < length; j1++)
			{
				//打印数字前加空格,使整体对齐
				if(10 > array[i1][j1])
					System.out.print("  " + array[i1][j1] + " ");
				else if(100 > array[i1][j1])
					System.out.print(" " + array[i1][j1] + " ");
				else
					System.out.print(array[i1][j1] + " ");
				
				//进行换行
				if(length- 1 == j1)
					System.out.println();
			}
		}

	}

}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值