核心在于数字增长规律,从左到右,从右往下,从右往左,从下往上,分别控制列、行固定,再实现数字增长。输出完每一层边界后,边界值要对应变化。
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cin >> n;
int arr[20][20] = { 0 };
int num = 1;
int top = 0;int bottom = n - 1;
int left = 0;int right = n - 1;
while (num <= n * n)
{
//上,左到右,i-列
for (int i = left;i <= right && (num <= n * n);i++)
{
arr[top][i] = num++;
}
top++;
//右,上到下,i-行
for (int i = top;i <= bottom && (num <= n * n);i++)
{
arr[i][right] = num++;
}
right--;
//下,右到左,i-列
for (int i = right;i >= left && (num <= n * n);i--)
{
arr[bottom][i] = num++;
}
bottom--;
//左,下到上,i-行
for (int i = bottom;i >= top && (num <= n * n);i--)
{
arr[i][left] = num++;
}
left++;
}
//打印
for (int i = 0;i < n;i++)
{
for (int j = 0;j < n;j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}

京公网安备 11010502036488号