java旋轉二維數組執行個體_java

來源:互聯網
上載者:User

本文執行個體講述了java旋轉二維數組的操作,分享給大家供大家參考。具體實現方法如下:

複製代碼 代碼如下:

package test;
/*
 *     1    2    3    4    5   
 *    16    17    18    19    6   
 *    15    24    25    20    7   
 *    14    23    22    21    8   
 *    13    12    11    10    9
 *
 *    寫一方法,列印等長的二維數組,要求從1開始的自然數由方陣的最外圈向內螺旋方式地順序排列。
 * */
public class Test6
{
    public static void main(String[] args)
    {
        arraynum(4);
    }
    // 便於改代碼..輸入不同y值輸出不同的二維數列
    private static void arraynum(int x)
    {
        int[][] arr = new int[x][x];
        int len = arr.length, max = 0, count = 0;
        specArr(arr, len, max, count);
        arrprint(arr);
    }
    // 進階for輸出列印用的
    private static void arrprint(int[][] arr)
    {
        for (int[] in : arr)
        {
            for (int t : in)
            {
                System.out.print(t + "\t");
            }
            System.out.println();
        }
    }
    private static void specArr(int[][] arr, int len, int max, int count)
    {
        while (len > 0)
        {
            int j = 0;
            for (int index = 0; index < (len - 1) * 4; index++)
            {
                if (index < len - 1)
                    arr[0 + count][index + count] = ++max;
                else if (index < 2 * (len - 1))
                    arr[count + j++][arr.length - 1 - count] = ++max;
                else if (index < 3 * (len - 1))
                    arr[arr.length - 1 - count][(j--) + count] = ++max;
                else if (index < 4 * (len - 1))
                    arr[arr.length - 1 - (j++) - count][0 + count] = ++max;
            }
            if (len == 1)
            {
                arr[arr.length / 2][arr.length / 2] = max + 1;
            }// 注意到 當y值為奇數時,會有迴圈到n=1的情況,需要補進數組最中間值
            count++;
            len = len - 2;
        }
    }
}

希望本文所述對大家的Java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.