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();//换行
            }
        }
  • 相关阅读:
    codevs1430 素数判定
    codevs1212 最大公约数
    codevs1012 最大公约数和最小公倍数问题
    codevs1160 蛇形矩阵
    Debate CodeForces
    Divide Candies CodeForces
    Login Verification CodeForces
    Colorful Bricks CodeForces
    ExaWizards 2019 English D
    Cards and Joy CodeForces
  • 原文地址:https://www.cnblogs.com/kaima/p/4773908.html
Copyright © 2011-2022 走看看