C++實現:螺旋矩陣的執行個體代碼

來源:互聯網
上載者:User

通過觀察發現矩陣的下標有這樣一個規律:a行遞增後b列遞增然後c行遞減再d列遞減,但是對應值卻是逐漸增加的。因此可用4個迴圈實現,需要注意的是在賦值時不要把之前的值覆蓋了。所以在這裡選擇相同顔色部分賦值,代碼如下:

複製代碼 代碼如下:#include <iostream>
#include <iomanip>

using namespace std;

// 輸出螺旋矩陣
void Matrix()
{
const int size = 10; // 矩陣大小
int matrix[size][size] = {0};

int row = 0;
int col = 0;

int start = 1; // 起始值
int temp = size;
for (int count = 0; count < size / 2; count++) // size階的矩陣可以畫size/2個圈
{
for (; col < temp - 1; col++) // a排賦值
matrix[row][col] = start++;
for (; row < temp - 1; row++) // b排賦值
matrix[row][col] = start++;
for (col = temp - 1; col > count; col--) // c排賦值
matrix[row][col] = start++;
for (row = temp - 1; row > count; row--) // d排賦值
matrix[row][col] = start++;

// 進入下一圈
temp--;
row++;
start -= 1; // 這裡-1是因為在換圈的時候會多加1
}

if (0 != size % 2) // 如果size為奇數則最後會有一個數遍曆不到,這裡補上
matrix[row][col+1] = start + 1;

// 輸出數組
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout << setw(5) << matrix[i][j];
}
cout << endl;
}
}

int main(int argc, char **argv)
{
Matrix();
return 0;
}

結果如下(分奇、偶數):

相關文章

聯繫我們

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