题目挺有意思 用笨方法写了写
#include
#include
#include
void chushi();
int **hui(int n);
int main(int argc, char const *argv[])
{
int n = 0;
printf("input number:\n");
scanf("%d", &n);
int r = ceil(sqrt(n));
int **b = hui(n);
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
printf("%5d ", *((int *)b + r * i + j));
}
printf("\n");
printf("\n");
}
return 0;
}
// 逆时针旋转 第一遍
void chushi()
{
int n = 36;
int r = ceil(sqrt(n));
int nums[n][n];
for (int x = 0; x < n; x++)
{
for (int y = 0; y < n; y++)
{
nums[x][y] = 0;
}
}
int j = r / 2;
int k = r / 2;
int f = 2;
int i = 1;
int c = 1;
while (1)
{
for (int l = 0; l < f; l++)
{
nums[j][k] = i;
i++;
k += c;
if (i == n + 1)
{
for (int x = 0; x < n; x++)
{
for (int y = 0; y < n; y++)
{
printf("%3d", nums[x][y]);
}
printf("\n");
}
return 1;
}
}
k -= c;
i--;
for (int l = 0; l < f; l++)
{
nums[j][k] = i;
i++;
j -= c;
if (i == n + 1)
{
for (int x = 0; x < n; x++)
{
for (int y = 0; y < n; y++)
{
printf("%3d", nums[x][y]);
}
printf("\n");
}
return 1;
}
}
j += c;
i--;
f++;
c = -c;
}
}
// 逆时针旋转 第二遍
int **hui(int n)
{
// 半径和初始坐标
int r = ceil(sqrt(n));
int j = r / 2;
int k = r / 2 + r % 2 - 1;
// 初始化
int **nums = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < r; i++)
{
nums[i] = (int *)malloc(n * sizeof(int));
}
for (int x = 0; x < r; x++)
{
for (int y = 0; y < r; y++)
{
*((int *)nums + r * x + y) = 0;
}
}
int f = 2; // 从2个开始循环
int i = 1; // n从小到大
int c = 1; // 符号转换器
while (1)
{
for (int l = 0; l < f; l++)
{
*((int *)nums + r * j + k) = i;
i++;
k += c;
if (i == n + 1)
{
return nums;
}
}
k -= c;
i--;
for (int l = 0; l < f; l++)
{
*((int *)nums + r * j + k) = i;
i++;
j -= c;
if (i == n + 1)
{
return nums;
}
}
j += c;
i--;
f++;
c = -c;
}
}