|
发表于 2003-6-30 20:55:26
|
显示全部楼层
11、图的建立及输出
任务:建立图的存储结构(图的类型可以是有向图、无向图、有向网、无向网,学生可以任选两种类型),能够输入图的顶点和边的信息,并存储到相应存储结构中,而后输出图的邻接矩阵。
要求:- #include <stdio.h>
- #define NUM 4
- struct head {
- int No;
- int visited;
- struct node *next;
- };
- struct node {
- int No;
- int link;
- struct node *next;
- };
- typedef struct head ehead;
- typedef struct node enode;
- void traversal(ehead *graph,int i);
- int matrix[NUM][NUM];
- main()
- {
- int i,j,linkdata;
- enode *p,*last;
- ehead graph[NUM];
- for(i=0;i<NUM;i++)
- for(j=0;j<NUM;j++)
- matrix[NUM][NUM]=0;
- printf("Please input the linkdata\n");
- for(i=0;i<NUM;i++)
- {
- graph[i].No=i;graph[i].next=NULL;graph[i].visited=0;
- for(j=0;j<NUM;j++)
- {
- if(i==j) continue;
- printf("link(%d,%d):",i+1,j+1);scanf("%d",&linkdata);
- if(linkdata==0) continue;
- p=(enode *)malloc(sizeof(enode));
- p->link=linkdata;p->next=NULL;p->No=j;
- if(graph[i].next==NULL) {graph[i].next=p;last=p;}
- else { last->next=p; last=p;}
- }
- }
- traversal(graph,0);
- for(i=0;i<NUM;i++)
- {
- for(j=0;j<NUM;j++)
- printf("%5d",matrix[i][j]);
- printf("\n");
- }
- }
- void traversal(ehead *graph,int i)
- {
- enode *last;
- last=graph[i].next;
- printf("%-5d\n",graph[i].No+1);
- graph[i].visited=1;
- while(last!=NULL)
- {
- // printf("link(%d,%d) :%d",i+1,last->No+1,last->link);
- matrix[i][last->No]=last->link;
- if(graph[last->No].visited==0)
- traversal(graph,last->No);
- else
- last=last->next;
- }
- }
- [root@localhost tmp]# ./a.out
- Please input the linkdata
- link(1,2):1
- link(1,3):2
- link(1,4):3
- link(2,1):0
- link(2,3):4
- link(2,4):0
- link(3,1):0
- link(3,2):0
- link(3,4):5
- link(4,1):0
- link(4,2):0
- link(4,3):0
- 1
- 2
- 3
- 4
- 0 1 2 3
- 0 0 4 0
- 0 0 0 5
- 0 0 0 0
复制代码 图为:其实有向图和无向图是一样的啦!只是在输入边权值的时候自己注意不要双向赋值就行了。代码写得很差。但有些问题我无法解决。不知道要怎么才能把matrix[][]放到main函数里。而且构造图的函数应该独立。有向网的以后再想想。 |
|