給定 n 階矩陣,按順時針螺旋順序列印所有元素。
輸入範例(n=4):
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
輸出:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
將矩陣視為同心圓層,每層由「左→右、上→下、右→左、下→上」四個線段組成。用對角線兩端點 (top, left)、(bottom, right) 界定當前圈層邊界,列印完一圈後向內收縮邊界,直到邊界交錯。

void PrintMatrixSpiral(int **mat, int n) {
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// 左→右
for (int j = left; j <= right; ++j) printf("%d ", mat[top][j]);
// 上→下
for (int i = top + 1; i <= bottom; ++i) printf("%d ", mat[i][right]);
// 右→左(需避免重複列印單行/單列)
if (top < bottom) {
for (int j = right - 1; j >= left; --j) printf("%d ", mat[bottom][j]);
}
// 下→上
if (left < right) {
for (int i = bottom - 1; i > top; --i) printf("%d ", mat[i][left]);
}
++top; --bottom; ++left; --right; // 向內收縮
}
}
int main() {
int n = 4;
int mat[4][4] = {{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}};
PrintMatrixSpiral((int**)mat, n);
return 0;
}
// 輸出: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

同樣邏輯可寫成尾遞迴:列印外圈 → 遞迴處理內部子矩陣。本質相同,迭代版效能略優且無堆疊溢位風險。
if 守衛top<=bottom && left<=right 自然涵蓋此題是陣列邊界控制與迴圈不變式的經典練習,面試高頻考點。