迴圈
輸入T
迴圈
輸入N M
設定矩陣
依M的值決定方向
設定矩陣值
輸出矩陣
釋放指標
#include <iostream>
#include <iomanip>
using namespace std;
void upSide(int M);
void downSide(int M);
void leftSide(int M);
void rightSide(int M);
int ** ary;
int value;
int UP, DOWN, LEFT, RIGHT;
int main()
{
int T, N, M;
while(cin >> T)
while(T--)
{
cin >> N >> M;
ary = new int* [N];
for(int i = 0; i<N; i++)
ary[i] = new int[N];
UP = 0, DOWN = N-1, LEFT = 0, RIGHT = N-1;
value = 1;
if(M == 1)
while(UP <= N/2)
{
upSide(M);
rightSide(M);
downSide(M);
leftSide(M);
}
else
while(LEFT <= N/2)
{
leftSide(M);
downSide(M);
rightSide(M);
upSide(M);
}
for(int i = 0; i<N; i++)
{
for(int j = 0; j<N; j++)
cout << ary[i][j] << setw(5);
cout << endl;
}
delete []ary;
}
return 0;
}
void upSide(int M)
{
if(M == 1)
for(int i = LEFT; i<=RIGHT; i++)
ary[UP][i] = value++;
else
for(int i = RIGHT; i>=LEFT; i--)
ary[UP][i] = value++;
UP++;
}
void downSide(int M)
{
if(M == 1)
for(int i = RIGHT; i>=LEFT; i--)
ary[DOWN][i] = value++;
else
for(int i = LEFT; i<=RIGHT; i++)
ary[DOWN][i] = value++;
DOWN--;
}
void leftSide(int M)
{
if(M == 1)
for(int i = DOWN; i>=UP; i--)
ary[i][LEFT] = value++;
else
for(int i = UP; i<=DOWN; i++)
ary[i][LEFT] = value++;
LEFT++;
}
void rightSide(int M)
{
if(M == 1)
for(int i = UP; i<=DOWN; i++)
ary[i][RIGHT] = value++;
else
for(int i = DOWN; i>=UP; i--)
ary[i][RIGHT] = value++;
RIGHT--;
}
留言列表