题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/f228a074c5274619b26be544962375e1
#include <stdio.h>
int main() {
int n;
scanf("%d",&n);
int arr[n][n];
int count=1;
for(int i=1;i<=(2*n-1);i++)
{
//控制向上还是向下,奇数向上。偶数向下
//向上
if(i%2!=0)
{
for(int x=i-1;x>=0;x--)
{
for(int y=0;y<i;y++)
{
//防止越界
if((x+y)==(i-1)&&x<n&&y<n)
{
arr[x][y]=count;
count++;
}
}
}
}
//向下
else
{
for(int x=0;x<i;x++)
{
for(int y=i-1;y>=0;y--)
{
if((x+y)==(i-1)&&x<n&&y<n)
{
arr[x][y]=count;
count++;
}
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
#题解#
查看3道真题和解析