蛇形输出

来源:互联网 发布:淘宝乐高日本代购 编辑:程序博客网 时间:2024/06/06 06:48
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();//换行        }    }
0 0
原创粉丝点击