輸入正整數 N (≤10),輸出 N×N 矩陣,將 1 到 N² 按順時針螺旋順序填入,從左上角開始向右。
維護四個邊界變量:top、bottom、left、right。按「右→下→左→上」四個方向循環填充,每完成一邊就向內收縮對應邊界,直到邊界交錯。
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int a[11][11] = {0};
int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
// 向右:頂行
for (int col = left; col <= right; col++)
a[top][col] = num++;
if (++top > bottom) break; // 收縮上邊界,檢查是否結束
// 向下:右列
for (int row = top; row <= bottom; row++)
a[row][right] = num++;
if (--right < left) break; // 收縮右邊界
// 向左:底行
for (int col = right; col >= left; col--)
a[bottom][col] = num++;
if (--bottom < top) break; // 收縮下邊界
// 向上:左列
for (int row = bottom; row >= top; row--)
a[row][left] = num++;
++left; // 收縮左邊界
}
// 輸出
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d", a[i][j]);
printf("\n");
}
return 0;
}
break),避免重複填充中心元素(奇數 N 時)top <= bottom && left <= right 確保還有未填充區域%3d 保證對齊,適配 1-3 位數字輸入:4 輸出: 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
只需調整四個方向的順序及邊界更新邏輯即可。例如逆時針:右→上→左→下,或從中心向外螺旋(需先計算中心坐標)。
// 邏輯完全一致,僅語法差異
while (upBound <= downBound && leftBound <= rightBound) {
for (int j = leftBound; j <= rightBound; j++) res[upBound][j] = num++;
if (++upBound > downBound) break;
for (int i = upBound; i <= downBound; i++) res[i][rightBound] = num++;
if (--rightBound < leftBound) break;
for (int j = rightBound; j >= leftBound; j--) res[downBound][j] = num++;
if (--downBound < upBound) break;
for (int i = downBound; i >= upBound; i--) res[i][leftBound] = num++;
++leftBound;
}