题目要求:输入n,打印一个蛇形图。如n=3,则打印出如下图形:
这个题目比较简单,就是要小心各种下标,很容易弄错。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n = 0;
int **p;
cin >> n;
p = new int*[n];
for (int i = 0; i < n; i++)
{
p[i] = new int[n];
}
int round = n / 2 - 1;
for (int i = 0; i <= round; i++)
{
int start1 = 4 * n * i - 4 * i*i + 1;
for (int j = 0; j < n - 2 * i; j++)
{
p[i][i + j] = start1+ j;
}
int start2 = start1 + (n - 2 * i) - 1;
for (int j = 0; j < n - 2 * i; j++)
{
p[i + j][n - i - 1] = start2 + j;
}
int start3 = start2 + (n - 2 * i) - 1;
for (int j = 0; j < n - 2 * i; j++)
{
p[n - i - 1][n - i - j - 1] = start3 + j;
}
int start4 = start3 + (n - 2 * i) - 1;
for (int j = 0; j < n - 2 * i - 1; j++)
{
p[n - 1 - i - j][i] = start4 + j;
}
}
if (n % 2 == 1)
{
p[n / 2][n / 2] = n*n;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << p[i][j] << " ";
}
cout << endl;
}
return 0;
}