zoukankan      html  css  js  c++  java
  • 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();//换行
            }
        }
  • 相关阅读:
    【后缀数组】poj2406 Power Strings
    [HNOI 2013]游走
    [HAOI 2008]木棍分割
    [SCOI 2010]传送带
    [SDOI 2010]魔法猪学院
    [Codeforces 235B]Let's Play Osu!
    [SPOJ 10628]Count on a tree
    [ZJOI 2010]count 数字计数
    [SHOI 2008]Debt 循环的债务
    [JSOI 2008]星球大战starwar
  • 原文地址:https://www.cnblogs.com/kaima/p/4773908.html
Copyright © 2011-2022 走看看