非遞迴演算法巧妙解決“螺旋方陣”問題

來源:互聯網
上載者:User

自訂螺旋矩陣的階長N,並將螺旋方陣存放到N×N的二維數組中並把它列印輸出。註:請尊重個人勞動成果,轉載請註明出處。

其實現代碼如下:

/*************************************************************************   檔案名稱  :  HelixMatrix.c                                             **   建立日期:  2012-8-15                                                 **   作者    :  Martin(p11234)                                            **   連絡方式:  Ma.Martin153@gmail.com                                    **   描述    :  自訂螺旋矩陣的階長N,並將螺旋方陣存放到                          **             N×N的二維數組中並把它列印輸出。                                    **   修改    :  無                                                                 **                                                                       **   聲明    :  本程式僅供學習交流,未經作者授權不得用於商業目的,          **             否則保留追究法律責任的權利。                                        **************************************************************************/#include <stdio.h>// 自訂的螺旋矩陣的階#define N 5int main(void){int index;          // 臨時計數單元int MaxIndex;       // 臨時計數單元的上界int tempRow;        // 臨時列計數單元int tempLine;       // 臨時行計數單元int MaxTemp;        // 臨時行列計數單元的上界int tempShowLine;   // 用於顯示螺旋矩陣的臨時行計數單元int tempShowRow;    // 用於顯示螺旋矩陣的臨時列計數單元int number= 0;      // 累加器int Matrix[N][N] = {0}; // 儲存螺旋矩陣的二維數組MaxIndex = ((N + 1) / 2 - 1);// 轉圈迴圈,為數組賦值for (index = 0; index <= MaxIndex; index++){tempRow = index;tempLine = index;MaxTemp = N - (index * 2 + 1) + index;// 左豎迴圈for (; tempRow < MaxTemp; tempRow++){Matrix[tempRow][tempLine] = (++number);}// 下橫迴圈for (; tempLine < MaxTemp; tempLine++){Matrix[tempRow][tempLine] = (++number);}// 右豎迴圈for (; tempRow > index; tempRow--){Matrix[tempRow][tempLine] = (++number);}// 上橫迴圈for (; tempLine > index; tempLine--){Matrix[tempRow][tempLine] = (++number);}}// 如果 N 為奇數if (1 == N % 2){Matrix[tempRow][tempLine] = (++number);}else{;}// 顯示螺旋矩陣printf("%d階螺旋矩陣如下所示:\n", N);for (tempShowRow = 0; tempShowRow < N; tempShowRow++){for (tempShowLine = 0; tempShowLine < N; tempShowLine++){printf("%-6d", Matrix[tempShowRow][tempShowLine]);}printf("\n\n");}return 0;}

當螺旋矩陣的階數是5時,其如下所示:

     

聯繫我們

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