用迴圈 40 行解決,不知道有沒有更乾淨的方法
#include <stdlib.h>
#include <iostream>
using namespace std;
int main() {
int T, M, N;
int R[100][100]; // 結果
cin >> T; // 測資數量
for (int i=0; i<T; i++) {
int n = 1; // 計數器 (繞多少)
cin >> N >> M; // 大小, 方向
for (int j=0; j<(N+1)/2; j++) { // 第幾層
for (int k=0; k<N-2*j-1; k++) // 上面
R[j][j+k] = n++;
for (int k=0; k<N-2*j-1; k++) // 右邊
R[j+k][N-j-1] = n++;
for (int k=0; k<N-2*j-1; k++) // 下面
R[N-j-1][N-k-j-1] = n++;
for (int k=0; k<N-2*j-1; k++) // 左邊
R[N-j-k-1][j] = n++;
}
if (N%2) // 奇數大小
R[N/2][N/2] = n; // 正中間
for (int j=0; j<N; j++) { // row
for (int k=0; k<N; k++) // col
if (M == 1) // 順時針
printf("%5d", R[j][k]);
else // 逆時針
printf("%5d", R[k][j]); // 行列交換
printf("\n");
}
printf("\n");
}
return 0;
}
差不多的行數 (34),簡化計算 index
#include <cstdio> int main() { short T, N, M, num; short mat[100][100]; scanf("%hd", &T); while (T--) { scanf("%hd%hd", &N, &M); num = 1; if (N & 1) mat[N / 2][N / 2] = N * N; for (short cth = 0, edge = N - 1; edge > 0; ++cth, edge -= 2) { short i = cth, j = cth; for (short e = 0; e < edge; ++e, ++j) mat[i][j] = (num++); for (short e = 0; e < edge; ++e, ++i) mat[i][j] = (num++); for (short e = 0; e < edge; ++e, --j) mat[i][j] = (num++); for (short e = 0; e < edge; ++e, --i) mat[i][j] = (num++); } for (short i = 0; i < N; ++i) { for (short j = 0; j < N; ++j) if (M == 1) printf("%5hd", mat[i][j]); else printf("%5hd", mat[j][i]); putchar('\n'); } putchar('\n'); } return 0; }