回形遍历方阵
输入一个整数n (n <= 10),构造一个n*n方阵,方阵数值从1开始递增,按照“右 下 左 上”的方式循环向内填充。? n = 4 ? 1? ? ?2? ?3? ? 4 ?12 ?13 ?14 ? 5 ?11 ?16 ?15? ?6 ?10? ? 9? ?8? ? 7
#include <stdio.h>
// 回形遍历方阵
int main()
{
int arr[10][10] = { 0 };
int num = 1;
int n;
int i, j;
scanf("%d", &n);
for (int m = 0, k = n - 1; m <= k; m++, k--)
{
for (i = m, j = m; j <= k; j++)//往右走
{
arr[i][j] = num++;
}
for (i = m + 1, j = k; i <= k; i++)//往下走
{
arr[i][j] = num++;
}
for (i = k, j = k - 1; j >= m; j--)//往左走
{
arr[i][j] = num++;
}
for (i = k - 1, j = m; i >= m + 1; i--)//往上走
{
arr[i][j] = num++;
}
}
//遍历输出
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%3d", arr[i][j]);
}
printf("\n");
}
}
|