题解 | #蛇形矩阵#
蛇形矩阵
https://ac.nowcoder.com/acm/problem/22231
本题只要找规律即可求解:
因为数组的下标是从0开始,为了方便我便创建一个a[n+1][n+1]大的二维数组,这样我就可以不用管索引0,直接从坐标(1,1)开始. n的范围是[1,1000],所以创建二维数组array[1001][1001] (我不知道编译器是否支持变长数组,所以就保险起见把所有范围都开了)
然后进行找规律,用思维蛇形矩阵举例:
(1,1)
(1,2)(2,1)
(3,1)(2,2)(1,3)
(1,4)(2,3)(3,2)(4,1)
(4,2)(3,3)(2,4)
(3,4)(4,3)
(4,4)
如下代码:
#include using namespace std; int n; int a[1001][1001]; int main(){ cin>>n; int k = 1;//用于赋值的数,从1开始,逐渐递增1
bool flag = true;
for(int i = 1; i <= n; i++){
int m = 1;
if(flag){
int left = i,right = m;
for(int j = 1; j <= i; j++){
//cout<<i<<" "<<m<<endl;
a[left--][right++]=k;
k++;
flag = false;
}
}else{
int left = m,right = i;
for(int j = 1; j <= i; j++){
//cout<<m<<" "<<i<<endl;
a[left++][right--]=k;
k++;
flag = true;
}
}
}
for(int i = 2; i<=n; i++){
int m = n;
if(flag){
int left = m,right = i;
for(int j = 1; j <= m-i+1; j++){
//cout<<left<<" "<<right<<endl;
a[left--][right++]=k;
//cout<<k<<endl;
k++;
flag = false;
}
}else{
int left = i,right = m;
for(int j = 1; j <= m-i+1; j++){
//cout<<left<<" "<<right<<endl;
a[left++][right--]=k;
//cout<<k<<endl;
k++;
flag = true;
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
} ———————————————— 版权声明:本文为CSDN博主「wangshuaiqi20310」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/wangshuaiqi20310/article/details/129510408