数据结构----图(邻接矩阵用法)

1、定义图的链接矩阵:

1 #define VERTEX_MAX 6
2 #define MAXVALUE 32767
3 typedef struct{
4     int vertex[VERTEX_MAX];
5     int edges[VERTEX_MAX][VERTEX_MAX];
6     int vertexNum,edgesNum;
7     int grapType;
8 }MatrixGraph;

2、定义函数createGraph,创建图的邻接矩阵:

 1 void createGraph(MatrixGraph *g){
 2     int start,end;
 3     printf("Please input  vertexs
");
 4     for(int i=0;i<g->vertexNum;i++){
 5         printf("the %d vertex is ",i+1);
 6         scanf("%d",&g->vertex[i]);
 7     }
 8     printf("
Please input the edges. The former is that the first input is the start vertex and the second input is the end vertex!
");
 9     for(int i=0;i<g->edgesNum;i++){
10         printf("the %d edge:(please input data like above!) ",i+1);
11         scanf("%d%d",&start,&end);
12         g->edges[start-1][end-1]=1;
13         if(g->grapType==0)
14         g->edges[end-1][start-1]=1;
15     }
16 }

3、定义函数输出邻居矩阵的内容:

 1 void printGraph(MatrixGraph *g){
 2     printf("  ");
 3     for(int i=0;i<g->vertexNum;i++){
 4         printf("%d ",g->vertex[i]);
 5     }
 6     for(int i=0;i<g->vertexNum;i++){
 7         printf("
%d ",g->vertex[i]);
 8         for(int j=0;j<g->vertexNum;j++){
 9             if(g->edges[i][j]==MAXVALUE)
10             printf("@ ");
11             else
12             printf("%d ",g->edges[i][j]);
13         }
14     }
15     printf("
");
16 }

4、主函数:

 1 int main(){
 2     MatrixGraph *g;
 3     g=(MatrixGraph *)malloc(sizeof(MatrixGraph));
 4     printf("Please select the type of grap: 0 is undigrap, 1 is digrap.
");
 5     scanf("%d",&g->grapType);
 6     printf("Please input the vertexNum and edgeNum of matrixGraph!
");
 7     scanf("%d%d",&g->vertexNum,&g->edgesNum);
 8     for(int i=0;i<g->vertexNum;i++){
 9         for(int j=0;j<g->vertexNum;j++){
10             g->edges[i][j]=MAXVALUE;
11         }
12     }
13     createGraph(g);
14     printf("Oupt the MatrixGrap. 
");
15     printGraph(g);
16     free(g);
17     getch();
18     return 0;
19 }

注意:主函数中的 

MatrixGraph *g;

可以改写成 

MatrixGraph g;
 1 printf("Please select the type of grap: 0 is undigrap, 1 is digrap.
");
 2     scanf("%d",&g.grapType);
 3     printf("Please input the vertexNum and edgeNum of matrixGraph!
");
 4     scanf("%d%d",&g.vertexNum,&g.edgesNum);
 5     for(int i=0;i<g.vertexNum;i++){
 6         for(int j=0;j<g.vertexNum;j++){
 7             g.edges[i][j]=MAXVALUE;
 8         }
 9     }
10     createGraph(&g);
11     printf("Oupt the MatrixGrap. 
");
12     printGraph(&g);
13     getch();
14     return 0;

但是后面指向结构体变量时需要用 . 而不是用->,并且需要给结构体指针变量先开辟空间 。

在c++中g如果是对象,就可以通过"."来调用I中的成员变量。
如果g是指针的话,就不能通过"."来调用,而只能使用"->"来调用。
在C语言中不存在对象的概念。
这种情况的出现是因为使用了结构,例如:

在程序中

1 MatrixGraph G; 

我们就可以用G.vertexNum来取得结构中的值。
这时是不能使用"->"来调用的,"->"符号指针对指针来说的。
如下情况可以使用"->"

1 MatrixGraph *g;

此时g为一个MatrixGraph结构的地址指针。所以可以使用"->",而此时就不能使用
"."来操作。因为"." "相当于"对象的成员调用。

最终显示结果:

原文地址:https://www.cnblogs.com/hoojjack/p/4563017.html