#include <iostream>
#include <iomanip>
using namespace std;
int matrix[101][101] = {0}, T, N, M;
int main() {
while ( cin >> T ) {
while ( T-- ) {
cin >> N >> M;
int cnt = 0;
if ( M == 1 ) {
for ( int layer = 0; layer <= N / 2; ++layer ) {
for ( int j = layer; j < N - layer; ++j )
matrix[layer][j] = ++cnt;
for ( int i = layer + 1; i < N - layer - 1; ++i )
matrix[i][N - layer - 1] = ++cnt;
for ( int j = N - layer - 1; j > layer; --j )
matrix[N - layer - 1][j] = ++cnt;
for ( int i = N - layer - 1; i > layer; --i )
matrix[i][layer] = ++cnt;
}
} else {
for ( int layer = 0; layer <= N / 2; ++layer ) {
for ( int i = layer; i < N - layer; ++i )
matrix[i][layer] = ++cnt;
for ( int j = layer + 1; j < N - layer; ++j )
matrix[N - layer - 1][j] = ++cnt;
for ( int i = N - layer - 2; i >= layer; --i )
matrix[i][N - layer - 1] = ++cnt;
for ( int j = N - layer - 2; j > layer; --j )
matrix[layer][j] = ++cnt;
}
}
for ( int i = 0; i < N; ++i ) {
for ( int j = 0; j < N; ++j )
cout << setw ( 5 ) << matrix[i][j];
cout << endl;
}
}
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int matrix[101][101] = {0}, T, N, M;
int main() {
while ( cin >> T ) {
while ( T-- ) {
cin >> N >> M;
for ( int layer = 0, cnt = 0; layer <= N / 2; ++layer ) {
for ( int j = layer; j < N - layer; ++j )
matrix[layer][j] = ++cnt;
for ( int i = layer + 1; i < N - layer - 1; ++i )
matrix[i][N - layer - 1] = ++cnt;
for ( int j = N - layer - 1; j > layer; --j )
matrix[N - layer - 1][j] = ++cnt;
for ( int i = N - layer - 1; i > layer; --i )
matrix[i][layer] = ++cnt;
}
for ( int i = 0; i < N; ++i ) {
for ( int j = 0; j < N; ++j )
cout << setw ( 5 ) << ( M == 1 ? matrix[i][j] : matrix[j][i] );
cout << endl;
}
}
}
return 0;
}
寫完後看了樓下高手SEAN大的解答
突然意識到原來順時針逆時針就是轉置矩陣的意思
精簡了一半的CODE