Java蛇形数组的简单实现代码

上周五和朋友聊天谈到个蛇形数组的java实现办法,命题是:假设一个二维数组宽w高h,从1开始蛇形输出

int[][] numberMatric = new int[w][h];

当时午睡过头脑袋不清醒,愣是没有好的思路。后来晚上研究了下,发现一种比较简单的实现办法。核心思路是:

找准移动方向,按移动顺序递增填充二维数组。

比较简单的实现办法如下:

private void snakeMatrix(int w, int h){
        int x,y;//维度
        int[][] numberMatric = new int[w][h];
        int num = numberMatric[x = 0][y = 0] = 1;
        while(num < w*h){
            //往右移动
            while(y+1<h && numberMatric[x][y+1] == 0/*未填充默认的项其值为0*/){
                y++;
                numberMatric[x][y] = ++num;
            }
            //往下移动
            while(x+1<w && numberMatric[x+1][y] == 0){
                x++;
                numberMatric[x][y] = ++num;
            }
            //往左移动
            while(y-1>=0 && numberMatric[x][y-1] == 0){
                y--;
                numberMatric[x][y] = ++num;
            }
            //往上移动
            while(x-1>=0 && numberMatric[x-1][y] == 0){
                x--;
                numberMatric[x][y] = ++num;
            }
        }
        //打印输出
        for(x = 0;x < w;x++){
            for(y = 0;y < h;y++){
                System.out.printf("%4d",numberMatric[x][y]);
            }
            System.out.println();//换行
        }
    }

 

posted @ 2015-08-31 19:38  Kai.Ma  阅读(2974)  评论(0编辑  收藏  举报