記錄一個面試算法題

這周在QQ羣裏看到一位朋友問了一個算法題,好像是他面試時遇到的,當時比較忙,大致看了下這個題目,一下子還沒有想出來該怎麼做,不過我覺得這個題目還是挺有意思的,把題目保存起來了,今天放假上午在圖書館學習時記起了這個題目,就思考了一會,有了思路。下午又有事耽擱去了,沒有來將它做完,只得晚上這會稍微閒暇一點,就把上午的思路轉換爲代碼來將它實現吧。

題目:

在命令行輸入一個自然數N,實現如下面實例:

N=3時:

123

894

765

N=6時:

 01  02  03  04  05  06 
 20  21  22  23  24  07 
 19  32  33  34  25  08 
 18  31  36  35  26  09 
 17  30  29  28  27  10 
 16  15  14  13  12  11 

解題思路:

我在畫圖軟件裏簡單畫了下,如下圖:

即一個數組的某個點可以走的路徑爲:右->下->左->上

然後按着這個順序一直循環,直到所有數字都填入到數組中

public class JavaTest {
    /**
     * 長度大小
     */
    private static int LENGTH = 6;

    public static void main(String[] args) {

        int max = LENGTH * LENGTH;
        int maxNumberWeiShu = (max + "").length();
        System.out.println("最大數的位數爲:" + maxNumberWeiShu);
        String formatStr = " %0" + maxNumberWeiShu + "d ";

        int[][] array = new int[LENGTH][LENGTH];

        int index = 1;
        int i = 0, j = 0;
        while (index < max) {
            while (j + 1 < LENGTH && array[i][j + 1] == 0) {
                array[i][++j] = index++;
                System.out.println("next  右");
            }
            while (i + 1 < LENGTH && array[i + 1][j] == 0) {
                array[++i][j] = index++;
                System.out.println("next  下");
            }
            while (j - 1 >= 0 && array[i][j - 1] == 0) {
                array[i][--j] = index++;
                System.out.println("next  左");
            }
            while (i - 1 > 0 && array[i - 1][j] == 0) {
                array[--i][j] = index++;
                System.out.println("next  上");
            }

        }

        for (int row = 0; row < LENGTH; row++) {
            for (int col = 0; col < LENGTH; col++) {

                System.out.printf(formatStr, array[row][col] + 1);
            }
            System.out.println();
        }
    }
}

當輸入爲7時,上面代碼的輸出爲:

最大數的位數爲:2
next  右
next  右
next  右
next  右
next  右
next  右
next  下
next  下
next  下
next  下
next  下
next  下
next  左
next  左
next  左
next  左
next  左
next  左
next  上
next  上
next  上
next  上
next  上
next  右
next  右
next  右
next  右
next  右
next  下
next  下
next  下
next  下
next  左
next  左
next  左
next  左
next  上
next  上
next  上
next  右
next  右
next  右
next  下
next  下
next  左
next  左
next  上
next  右
 01  02  03  04  05  06  07 
 24  25  26  27  28  29  08 
 23  40  41  42  43  30  09 
 22  39  48  49  44  31  10 
 21  38  47  46  45  32  11 
 20  37  36  35  34  33  12 
 19  18  17  16  15  14  13 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章