蛇形矩阵(指针与动态内存分配)
题目描述
蛇形矩阵,是由1开始的自然数一次排列成的N*N的正方形矩阵,数字依次由外而内的递增。如 N=3时蛇形矩阵为:
1 2 3
8 9 4
7 6 5
N=6时蛇形矩阵为:
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
输入蛇形矩阵宽度,动态分配二维数组,设置蛇形矩阵并输出结果。
输入
测试次数t
每组测试数据一行:数组大小N(>0)
输出
对每组测试数据,输出计算得到的蛇形矩阵。每行元素间以空格分隔,最后一个元素后无空格。
每组测试数据之间以空行分隔。
样例输入
3
3
6
2
样例输出
1 2 3
8 9 4
7 6 5
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
1 2
4 3
#include <iostream>
using namespace std;
void getSnakeMatrix(int **snake_matrix,int N)
{
int row=0,column=0,num=1;
while (num<=N*N)
{
while (column<N && snake_matrix[row][column]==0)
snake_matrix[row][column++] = num++;
row++;
column--;
while (row<N && snake_matrix[row][column]==0)
snake_matrix[row++][column] = num++;
row--;
column--;
while (column>=0 && snake_matrix[row][column]==0)
snake_matrix[row][column--] = num++;
row--;
column++;
while (row>=0 && snake_matrix[row][column]==0)
snake_matrix[row--][column] = num++;
column++;
row++;
}
}
int main()
{
int t;
cin>>t;
while (t--)
{
int N;
cin>>N;
int **snake_matrix = new int*[N];
for(int i=0;i<N;i++)
{
snake_matrix[i] = new int[N];
for(int j=0;j<N;j++)
snake_matrix[i][j] = 0;
}
getSnakeMatrix(snake_matrix,N);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
cout<<snake_matrix[i][j];
if(j!=N-1)
cout<<" ";
else
cout<<endl;
}
}
cout<<endl;
for(int i=0;i<N;i++)
delete []snake_matrix[i];
delete []snake_matrix;
}
return 0;
}