#12541: C++簡易參考解答


shawn2000100 (東華財金)

學校 : 國立東華大學
編號 : 57300
來源 : [27.53.168.5]
最後登入時間 :
2021-09-19 19:53:19
a417. 螺旋矩陣 | From: [134.208.3.49] | 發表日期 : 2017-08-10 14:47

#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;
}

 
#12542: Re:C++簡易參考解答


shawn2000100 (東華財金)

學校 : 國立東華大學
編號 : 57300
來源 : [27.53.168.5]
最後登入時間 :
2021-09-19 19:53:19
a417. 螺旋矩陣 | From: [134.208.3.49] | 發表日期 : 2017-08-10 14:53

 

#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

 
ZeroJudge Forum