閱讀115 返回首頁    go 阿裏雲 go 技術社區[雲棲]


蛇形填 數

蛇形填數
時間限製:3000 ms | 內存限製:65535 KB
難度:3

描述
在n*n方陳裏填入1,2,...,n*n,要求填成蛇形。例如n=4時方陳為:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4

輸入
直接輸入方陳的維數,即n的值。(n<=100)
輸出
輸出結果是蛇形方陳。
樣例輸入

3

樣例輸出

7 8 1
6 9 2
5 4 3

細心的朋友可以發現一個特點,

要填 數,其實就是一圈一圈的填 數,

一圈就是4個循環,分別處理右列,下行,左列,上行。

好像是一個漩渦似的。

代碼如下:

#include <iostream>
#include <cstring>
using namespace std;
#define MAX_SIZE 100

int main()
{
    int n;
    cin >> n;//n * n方陣

    int pn[MAX_SIZE][MAX_SIZE];
    int row =-1, col = n-1;
    memset(pn, 0, sizeof(pn));
    int count = 1;
    while (count <= n * n)
    {
        while (row < n-1 && pn[row+1][col] == 0) pn[++row][col] = count++;
        while (col >= 1 && pn[row][col-1] == 0) pn[row][--col] = count++;
        while (row >= 1 && pn[row-1][col] == 0) pn[--row][col] = count++;
        while (col < n-1 && pn[row][col+1] == 0) pn[row][++col] = count++;
        //cout <<"count=" << count << endl;
    }

    for (int i = 0; i < n; i++)
    {
         for (int j = 0; j < n; j++)
             cout << pn[i][j] << " ";
         cout << endl;
    }

    return 0;
}



最後更新:2017-04-02 15:14:53

  上一篇:go 兄弟郊遊問題
  下一篇:go n-1位數