#include<iostream>
#include<iomanip>
using namespace std;
int main() {
const int MAX = 8;
int a[MAX][MAX] = { 0 };
int n;
cin >> n;
int num = 1;
int bottom = n - 1, left = 0, right = n - 1, top = 0;
while (top <= bottom && left <= right) {
if (top <= bottom) {
for (int i = left; i <= right; i++)
{
a[top][i] = num++;
}
top++;
}
if (left <= right) {
for (int i = top; i <= bottom; i++)
{
a[i][right] = num++;
}
right--;
}
if (top <= bottom) {
for (int i = right; i >= left; i--) {
a[bottom][i] = num++;
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
a[i][left] = num++;
}
left++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout<<setw(3) << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
看起来简单但是写起来是真要命
改了又改终于是做出来了。
简单说一下四个循环然后边界if来保证不越界。然后最后for循环输出数据。
紫皮书的话是c语言实现的而且代码十分的节俭高度凝练了。我没怎么看明白。所以还是建议初学的话都自己亲自打一打代码。不断的调试。