編程練習-螺旋數組

來源:互聯網
上載者:User

題目如下

===========

43 44 45 46 47 ..    ..
42 21 22 23 24 25 26
41 20 07 08 09 10 27
40 19 06 01 02 11 28
39 18 05 04 03 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31

看清以上數字排列的規律, 設1點的座標是(0,0), x方向向右為正, y方向向下為正. 例如, 7的座標為(-1,-1), 2的座標為(0,1), 3的座標為(1,1). 編程實現輸入任意點的座標, 輸出所對應的數字.

===========

我自己做的答案貼在下面. 在VC上調試通過.

標準答案還沒看, 太晚了. 改天再研究一下貼上來吧.

#include <iostream>#include <cmath>using namespace std;int iMatrix[100][100];void FillEdge(int width, int layer){    // Up right corner    int temp = iMatrix[layer][width - 1 - layer] = (width - layer - layer) * (width - layer -layer);    // Up edge    for( int i = width - 1 - layer; i >= layer; --i)        iMatrix[layer][i] = temp--;    // Left edge    for( int j = 1 + layer; j < width - layer; ++j)        iMatrix[j][layer] = temp--;    // Low edge    for( int i = 1 + layer; i < width - layer; ++i)        iMatrix[width - 1 - layer][i] = temp--;    // Right edge    for( int j = width - 2 - layer; j > layer; --j)        iMatrix[j][width - 1 - layer] = temp--;}void Print(int width){    for(int i = 0; i < width; i++)    {        for(int j = 0; j < width; j++)        {            cout<<iMatrix[i][j]<<"\t";        }        cout<<endl;    }    cout<<endl;}int main(){    memset(iMatrix, 0, sizeof(iMatrix));    cout << "螺旋數組" << endl;        int x = 0;     int y = 0;        cin >> x;    cin >> y;        int iBigger = 0;    if(abs(x) >= abs(y))        iBigger = abs(x);    else        iBigger = abs(y);    int width = 2 * iBigger + 1;        for(int w = 0; w <= iBigger; w++)    {        FillEdge(width, w);    }    Print(width);    cout<<iMatrix[y + iBigger][x + iBigger];}

 

題目來源:

<程式員面試寶典>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.