输入一个矩阵的行列数量,生成一个螺旋矩阵,比如输入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();
}
}
}
}