通過觀察發現矩陣的下標有這樣一個規律: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;
}
結果如下(分奇、偶數):