任给一个整数n,建立一个螺旋形矩阵A[n][n]。

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


public   class  Main  {
    
public   static   void  main(String[] args)  {
        
//  TODO Auto-generated method stub
         int  n = 5 ;
        
int  [][]table = new   int  [n + 2 ][n + 2 ];
        
// 初始化
         int  i,j;
        
for (i = 0 ;i <= n + 1 ;i ++ {
            
for (j = 0 ;j <= n + 1 ;j ++ )
                table[i][j]
=- 1 ;
        }

        
for (i = 1 ;i <= n;i ++ {
            
for (j = 1 ;j <= n;j ++ )
                table[i][j]
= 0 ;
        }

        
// 创建
        
        
int  row = 1 ; int  column = 1 ; int  k;
       
//  table[1][1]=1;
         int  dire = 0 ; // 0右,1下,2左,3上
         for (k = 1 ;k <= n * n;)  {
            
if (dire == 0 { // 方向为右
                table[row][column] = k ++ ;
                
if (table[row][column + 1 ] == 0 ) {
                    column
++ ;
                }
else {
                    dire
= 1 ; // 改方向为下
                    row ++ ;
                }

                
continue ;
            }

            
if (dire == 1 { // 方向为下
                table[row][column] = k ++ ;
                
if (table[row + 1 ][column] == 0 ) {
                    row
++ ;
                }
else {
                    dire
= 2 ; // 改方向为左
                    column -- ;
                }

                 
continue ;
            }

            
if (dire == 2 { // 方向为左
                table[row][column] = k ++ ;
                
if (table[row][column - 1 ] == 0 ) {
                    column
-- ;
                }
else {
                    dire
= 3 ; // 改方向为右
                    row -- ;
                }

                 
continue ;
            }

            
if (dire == 3 { // 方向为上
                table[row][column] = k ++ ;
                
if (table[row - 1 ][column] == 0 ) {
                    row
-- ;
                }
else {
                    dire
= 0 ; // 改方向为右
                    column ++ ;
                }

                 
continue ;
            }

        }

        
        
// 输出
         for (row = 1 ;row <= n;row ++ {
            
for (column = 1 ;column <= n;column ++ )
                System.out.print(table[row][column]
+ "      " );
            System.out.println();}

        
    }

}

当然,这个程序还有很多可以优化的地方。在此就不多说了。