解题思路:
奇阶幻方用爬楼梯法填 可以想象成立体圆柱 只要右上方没数就往右上方填 到顶了就从底填起 要是要填的格子有数 就填入上一个数的下方 如果还有 就重复找前一个数的下方
注意事项:
参考代码:
#include <stdio.h>
int n;
void digui(int i, int x, int *row, int *col, int num[30][30]);
int main(void)
{
while (scanf("%d", &n) != EOF)
{
int i = 1, x, row, col;
int num[30][30] = { 0 };
i = 2;
row = 0;
col = n / 2;
num[row][col] = 1;
if (n == 0)
break;
x = n*n - 1;
while (x--)
{
if (row - 1 < 0 && col + 1 < n)
{
if (num[n - 1][col + 1] == 0)
{
num[n - 1][col + 1] = i;
row = n - 1;
col = col + 1;
}
else
{
row = row + 1;
digui(i, i, &row, &col, num);
}
}
else if (row - 1 >= 0 && col + 1 >= n)
{
if (num[row - 1][0] == 0)
{
num[row - 1][0] = i;
row = row - 1;
col = 0;
}
else
{
row = row + 1;
digui(i, i, &row, &col, num);
}
}
else if (row - 1 < 0 && col + 1 >= n)
{
if (num[n - 1][0] == 0)
{
num[n - 1][0] = i;
row = n - 1;
col = 0;
}
else
{
row = row + 1;
digui(i, i, &row, &col, num);
}
}
else
{
if (num[row - 1][col + 1] != 0)
{
row = row + 1;
digui(i, i, &row, &col, num);
}
else
{
num[row - 1][col + 1] = i;
row = row - 1;
col = col + 1;
}
}
i++;
}
if (n*n - 1 < 10)
{
for (i = n - 1;i >= 0;i--)
{
int j;
for (j = 0;j < n;j++)
{
printf("%d", num[i][j]);
if (j != n - 1)
printf(" ");
}
printf("\n");
}
}
else if (n*n - 1 < 100)
{
for (i = n - 1;i >= 0;i--)
{
int j;
for (j = 0;j < n;j++)
{
printf("%2d", num[i][j]);
if (j != n - 1)
printf(" ");
}
printf("\n");
}
}
else
{
for (i = n - 1;i >= 0;i--)
{
int j;
for (j = 0;j < n;j++)
{
printf("%3d", num[i][j]);
if (j != n - 1)
printf(" ");
}
printf("\n");
}
}
printf("\n");
}
return 0;
}
void digui(int i, int x, int *row, int *col, int num[30][30])
{
if (num[*row][*col] == 0)
{
num[*row][*col] = x;
return;
}
else
{
int k, l;
for (k = 0;k < n;k++)
{
int flag = 0;
for (l = 0;l < n;l++)
{
if (num[k][l] == i)
{
flag = 1;
break;
}
}
if (flag == 1)
break;
}
*row = k + 1;
*col = l;
digui(i - 1, x, row, col, num);
}
}
0.0分
2 人评分
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:543 |
简单的for循环浏览:1411 |
校门外的树 (C语言代码)浏览:702 |
WU-C语言程序设计教程(第三版)课后习题12.1 (C++代码)浏览:941 |
C语言程序设计教程(第三版)课后习题9.8 (C语言代码)浏览:616 |
sizeof的大作用 (C语言代码)浏览:1452 |
The 3n + 1 problem (C语言代码)浏览:505 |
C语言程序设计教程(第三版)课后习题7.5 (C语言代码)浏览:555 |
班级人数 (C语言代码)浏览:927 |
JAM计数法 (C语言代码)浏览:671 |