輸入N,螺旋打印N邊正方形

簡單模擬題(某金融公司面試題)

Input&Output:

輸入N,在控制檯上輸出初始邊長爲N的圖案

測試樣例:

輸入:10

輸入:7

思路:觀察打印圖形總結出如下規律(以N=10爲例):

1.從(0,0)座標開始橫向往右打印10個*

2.從(1,9)開始縱向往下打印9個*

3.從(10,9)開始橫向往左打印8個*

4.從(8,1)開始縱向往上打印7個*

5.安裝1-4步驟循環執行,知道打印一個*

Java實現如下:

public class DrawMap {
    /**
     * 輸入N,螺旋打印N邊正方形
     * @param
     */
    public static void draw(int n ) {
        boolean[][] flag = new boolean[n+1][n+1];
        int t = 0;
        int x = 0,y = 0;
        for (int c = n; c > 0; c--) {
            if (t%4 == 0) { //橫着往前畫->
                int num = 0;
                while (num < c) {
                    flag[x][y + num] = true;
                    num ++;
                }
                y = y + num - 1;
                x = x + 1;
                t += 1;
            } else if (t%4 == 1){//豎着往下畫
                int num = 0;
                while (num < c) {
                    flag[x + num][y] = true;
                    num ++;
                }
                x = x + num -1 ;
                y = y - 1;
                t += 1;
            } else if (t%4 == 2) { //橫着往前畫
                int num = 0;
                while ( num < c) {
                    flag[x][y - num] = true;
                    num ++;
                }
                x = x - 1;
                y = y - num + 1;
                t += 1;
            } else if (t%4 == 3) { //豎着往上畫
                int num = 0;
                while (num < c) {
                    flag[x - num][y] = true;
                    num ++ ;
                }
                x = x - num + 1;
                y = y + 1;
                t += 1;
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (flag[i][j]) System.out.print("*");
                else System.out.print(" ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        draw(10);
        System.out.println("==============");
        draw(5);
        System.out.println("==============");
        draw(7);
        System.out.println("==============");
        draw(1);
    }
}

 

 

 

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