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();//換行
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM