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();//换行
        }
    }
复制代码

 

本文转自Kai的世界,道法自然博客园博客,原文链接:http://www.cnblogs.com/kaima/p/4773908.html,如需转载请自行联系原作者。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值