代码如下:
描述
给你一个整数n,输出n∗n的蛇形矩阵。
输入描述:
输入一行,包含一个整数n
输出描述:
输出n行,每行包含n个正整数,通过空格分隔。
1<=n<=1000
代码如下:
#include <stdio.h>
int main()
{
int n = 0;
scanf("%d", &n);
int count = 1;
int row = 0, col = 0;
int arr[50][50] = { 0 };
int i = 0;
while (count <= n * n)
{
for (i = 0; i < 2; i++)
{
if (row < n && col < n)
{
arr[row][col] = count++;
}
col++;
}
col--;
while (col)
{
row++;
col--;
if (row < n && col < n)
{
arr[row][col] = count++;
}
}
row++;
while (row)
{
if (row < n && col < n)
{
arr[row][col] = count++;
}
row--;
col++;
}
}
for (row = 0; row < n; row++)
{
for (col = 0; col < n; col++)
{
printf("%d ", arr[row][col]);
}
printf("\n");
}
return 0;
}