问题描述:
拉丁方阵是一种n×n的方阵,方阵中恰有n中不同的元素,每种元素恰有n个,并且每种元素在一行和一列中恰好出现一次。著名数学家和物理学家欧拉使用拉丁字母来做为方阵里元素的符号,拉丁方阵因此而得名。
问题分析:
用循环链表来实现
实现代码(c):
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct Node *LinkList;
//构造一个带有N个结点的循环链表
Node* CreatLists(struct Node *La,int n)
{
int i;
struct Node *p,*s;
La = (LinkList)malloc(sizeof(Node));
La->next = NULL;
p = La;
for(i = 1;i <= n;i++)
{
s = (LinkList)malloc(sizeof(Node));
s->data = i;
s->next = p->next;
p->next = s;
p = p->next;
}
p->next = La->next;
return p->next;
}
//实现拉丁方阵的输出
void print(struct Node *La,int n)
{
int i,j;
struct Node *p,*q;
p = La;
for(i = 1;i <= n;i++)
{
q = p;
for(j = 1;j <= n;j++)
{
printf("%3d",q->data);
q = q->next;
}
printf("\n");
p = p->next;
}
}
int main (int argc,char* argv[])
{
int m;
struct Node *L,*t;
while(1)
{
printf("****************************************************\n");
printf("***** ESC键: 退出程序 *****\n");
printf("***** *****\n");
printf("***** 其他任意键:打印拉丁方阵 *****\n");
printf("****************************************************\n");
if(getch() == 27)
break;
else
{
printf("\n请输入您要打印的拉丁方阵规模(要打印的行数):\n\n");
scanf("%d",&m);
L = CreatLists(L,m);
printf("\n您输入的规模为%d,打印的方阵如下:\n\n",m);
print(L,m);
printf("\n请输入任意键继续:\n");
getch();
system("cls");
}
}
return 0;
}