您的位置:首页 > 理论基础 > 数据结构算法

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

2015-06-09 11:47 274 查看
1、定义图的链接矩阵:

#define VERTEX_MAX 6
#define MAXVALUE 32767
typedef struct{
int vertex[VERTEX_MAX];
int edges[VERTEX_MAX][VERTEX_MAX];
int vertexNum,edgesNum;
int grapType;
}MatrixGraph;


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

void createGraph(MatrixGraph *g){
int start,end;
printf("Please input  vertexs\n");
for(int i=0;i<g->vertexNum;i++){
printf("the %d vertex is ",i+1);
scanf("%d",&g->vertex[i]);
}
printf("\nPlease input the edges. The former is that the first input is the start vertex and the second input is the end vertex!\n");
for(int i=0;i<g->edgesNum;i++){
printf("the %d edge:(please input data like above!) ",i+1);
scanf("%d%d",&start,&end);
g->edges[start-1][end-1]=1;
if(g->grapType==0)
g->edges[end-1][start-1]=1;
}
}


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

void printGraph(MatrixGraph *g){
printf("  ");
for(int i=0;i<g->vertexNum;i++){
printf("%d ",g->vertex[i]);
}
for(int i=0;i<g->vertexNum;i++){
printf("\n%d ",g->vertex[i]);
for(int j=0;j<g->vertexNum;j++){
if(g->edges[i][j]==MAXVALUE)
printf("@ ");
else
printf("%d ",g->edges[i][j]);
}
}
printf("\n");
}


4、主函数:

int main(){
MatrixGraph *g;
3     g=(MatrixGraph *)malloc(sizeof(MatrixGraph));
printf("Please select the type of grap: 0 is undigrap, 1 is digrap.\n");
scanf("%d",&g->grapType);
printf("Please input the vertexNum and edgeNum of matrixGraph!\n");
scanf("%d%d",&g->vertexNum,&g->edgesNum);
for(int i=0;i<g->vertexNum;i++){
for(int j=0;j<g->vertexNum;j++){
g->edges[i][j]=MAXVALUE;
}
}
createGraph(g);
printf("Oupt the MatrixGrap. \n");
printGraph(g);
16     free(g);
getch();
return 0;
}


注意:主函数中的

MatrixGraph *g;


可以改写成

MatrixGraph g;


printf("Please select the type of grap: 0 is undigrap, 1 is digrap.\n");
scanf("%d",&g.grapType);
printf("Please input the vertexNum and edgeNum of matrixGraph!\n");
scanf("%d%d",&g.vertexNum,&g.edgesNum);
for(int i=0;i<g.vertexNum;i++){
for(int j=0;j<g.vertexNum;j++){
g.edges[i][j]=MAXVALUE;
}
}
createGraph(&g);
printf("Oupt the MatrixGrap. \n");
printGraph(&g);
getch();
return 0;


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

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

在程序中

1 MatrixGraph G;


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

1 MatrixGraph *g;


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

最终显示结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: