编程实现N*N螺旋方阵:
如输入5,
输出结果:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
代码实现:
Java:
//用direction代表方向,0为右,1为下,2为左,3为上
import java.util.Scanner;
publicclassWelcome{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Pleaseinput the rowlength of the matrix: ");
int n= input.nextInt();
int N= n;
int count = n*n;
int direction = 0;
int [][] matrix = new int[n][n];
int row = 0;
int col = 0;
for(int k=1;k<=count;k++)
switch(direction)
{
case0:
matrix[row][col]=k;
if(col==n-1)
{
direction=1;
++row;
break;
}
++col;
break;
case1:
matrix[row][col]=k;
if(row==n-1)
{
--col;
direction=2;
break;
}
++row;
break;
case2:
matrix[row][col]=k;
if(col==N-n)
{
--row;
direction=3;
break;
}
--col;
break;
case3:
matrix[row][col]=k;
if(row==N-n+1)
{
++col;
direction=0;
--n;
break;
}
--row;
break;
}
System.out.println();
for(inti=0;i<N;i++)
for(intj=0;j<N;j++)
{
System.out.print(matrix[i][j]+" ");
if(j==N-1)System.out.println();
}
}
在网上找到了几篇不错的相关的文章,贴在这里:
n阶螺旋方阵的算法分析
http://wenku.baidu.com/link?url=39oCQYJfH5--fBGG5s4tINlYit1Db_gsixQ90J_bnr0NAqS3QRYJPMovitBApAF0jIHl4eh6dmqEkwJXeIa5yDJBjgFkdRB0wVlRfpBvU2S
C++打印螺旋方阵
http://zhidao.baidu.com/link?url=iC6uBz_cTgRIxdlSJ1f9w4_RByNja1208-uYbd4sy_gU9-pLq_jSSu7pErIwyk1O2sIP6ytFXIfs02ddeym3k9p8o1l_avPwAvpaNMdfra_