题解 | 回型矩阵
回型矩阵
https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
#include <stdio.h>
#define N 20
int main()
{
int n;
scanf("%d",&n);
int arr[N][N] = {0};
int i,j;
int top = 0;
int left = 0;
int right = n-1;
int bottom = n-1;
int count = 0;
while(count < n*n)
{
for(j = left; j <= right&&count < n*n; j++)
{
count++;
arr[top][j] = count;
}
top++;
for(i = top; i <= bottom&&count < n*n; i++)
{
count++;
arr[i][right] = count;
}
right--;
if(top <= bottom)
{
for(j = right; j >= left&&count < n*n; j--)
{
count++;
arr[bottom][j] = count;
}
bottom--;
}
if(left <= right)
{
for(i = bottom; i >= top&&count < n*n;i--)
{
count++;
arr[i][left] = count;
}
left++;
}
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}

查看1道真题和解析