要求输出格式为
 1    2    3    4
 12   13   14   5
 11   16   15   6
 10   9    8    7
     要求:简单的for循环应用,不要用引用API的方法
     扩展: 可以任意输出此格式!比如 25,输出5行5列按此排列!
    

解决方案 »

  1.   

    本帖最后由 AWUSOFT 于 2009-08-13 13:30:48 编辑
      

  2.   

    螺旋矩阵
      http://topic.csdn.net/u/20080114/22/48153ab5-a7ea-4246-972b-5e4c9f868430.html
      

  3.   

    import java.util.*;
    public class CycleSquare{
        public static void main(String[] args) {
         int[][] result=getSquare(5);
         printSquare(result);
        }
        public static int[][]getSquare(int x){
         int[][] direction={{0 , 1},  //offset of row and column when direction is east.
                        {1 , 0},  //south
                        {0 ,-1},  //west
                        {-1, 0}  //north
         };
         int[][] result=new int[x][x];
         int row=0,column=0;
         int num=1;
         int d=0;  //east
         int nextRow=0,nextColumn=0;
        
         while(num<=x*x){
         result[row][column]=num++;
         nextRow=row+direction[d][0];
         nextColumn=column+direction[d][1];
         if(nextRow==x||nextColumn==x||nextRow<0||nextColumn<0||result[nextRow][nextColumn]!=0){
         d=(d+1)%4;
         }
         row+=direction[d][0];
         column+=direction[d][1];
         }
         return result;
        }
        
        public static void printSquare(int[][] arr){
         for(int i=0;i<arr.length;i++){
         for(int j=0;j<arr[i].length;j++){
         System.out.printf("%5d",arr[i][j]);
         }
         System.out.println();
         }
        }}F:\java>java  CycleSquare
        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
      

  4.   

    F:\java>java  CycleSquare
        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
      

  5.   

    lz第一次发帖  就gf了!