描述如下:
n=1时:
输出 0 1 0
    4 5 2
    0 3 0
n=2时:
输出:
    0  1 2  0
   8  9 10 3
   7 12 11 4
   0  6  5  0
 依次类推,螺旋输出。

解决方案 »

  1.   


    public class HelixTest
    {
    private static int[][] helixNum(int n) {
    int len=n+2;
    int[][] array=new int[len][len];
            int count = len*len-4;
            int direct = 0;
            int round = 1;
            for(int index = 1, x = 0, y = 0; index <= count; index++) {
    if(((x==0)&&(y==0||y==len-1))||(x==len-1)&&(y==0||y==len-1)){
    array[x][y]=0;
    index--;
    }
    else{
    array[x][y] = index;
    }
                switch(direct) {
                    case 0: 
                        if(y < len - round)
                            y++;
                        else {
                            direct = 1;
                            x++;
                        }
                        break;
                    case 1:
                        if(x < len - round)
                            x++;
                        else {
                            direct = 2;
                            y--;
                        }
                        break;
                    case 2:
                        if(y >= round)
                            y--;
                        else {
                            direct = 3;
                            x--;
                        }
                        break;
                    case 3:
                        if(x > round)
                            x--;
                        else {
                            direct = 0;
                            round++;
                            y++;
                        }
                        break;                        
                }
            }
    return array;
        }
    public static void main(String[] args){
    int[][] intArr=helixNum(2);
    for(int i=0;i<intArr.length;i++){
    for(int j=0;j<intArr[i].length;j++){
    System.out.print(intArr[i][j]+" ");
    }
    System.out.println();
    } }
    }