//有向图的邻接矩阵#defineMaxVertexNum10//最大顶点数目typedefchar V;//顶点的数据类型typedefint E;//边的权值的数据类型typedefstruct{
V vex[MaxVertexNum];//顶点表
E edge[MaxVertexNum][MaxVertexNum];//邻接矩阵int vexnum, edgenum;//图的顶点数和弧数}MGraph;
操作
//判断图G是否存在边<x, y>
bool Adjacent(MGraph G,int x,int y){if(G.edge[x][y]==1){return true;}return false;}//列出图G中与结点x邻接的边voidNeighbors(MGraph G, V x){int item =0;while(G.vex[item]!= x){
item++;if(item >= MaxVertexNum){printf("没有与%c相邻的边\n", x);return;}}int k =0;printf("与%c相邻的边有:", x);while(k < MaxVertexNum){if(G.edge[item][k]==1){printf("(%d, %d)", item, k);}
k++;}printf("\n");}//在图G中插入顶点voidInsertVertex(MGraph& G, V x){int length = G.vexnum;if(length < MaxVertexNum){//插入顶点
G.vex[length]= x;
G.vexnum++;}else{printf("顶点数以及达到最大!\n");}}//在图G中删除结点voidDeleteVertex(MGraph&G, V x){int item =0;while(G.vex[item]!= x){
item++;if(item >= MaxVertexNum){printf("没有%c结点\n", x);return;}}
G.vex[item]=NULL;for(int i = item+1; i < MaxVertexNum; i++){
G.vex[i -1]= G.vex[i];}for(int i =0; i < MaxVertexNum; i++){if(G.edge[item][i]>0){
G.edge[item][i]=0;
G.edgenum--;}if(G.edge[i][item]>0){
G.edge[i][item]=0;
G.edgenum--;}}
G.vexnum--;}//若边<x, y>存在,则向图G中添加该边voidAddEdge(MGraph& G,int x,int y, V value){if(Adjacent(G, x, y)){printf("图中已经存在该边\n");}else{if(G.vex[x]<0|| G.vex[y]<0){printf("图中未存在该顶点\n");}else{
G.edge[x][y]= value;
G.edgenum++;}}}//删除边voidRemoveEdge(MGraph& G,int x,int y){if(Adjacent(G, x, y)){
G.edge[x][y]=0;
G.edgenum--;}else{printf("图中未存在该边\n");}}//设置边的值voidSet_edge_value(MGraph& G,int x,int y, V value){if(Adjacent(G, x, y)){
G.edge[x][y]= value;}else{printf("该边不存在\n");}}//获取边的值
E Get_edge_value(MGraph G,int x,int y){if(Adjacent(G, x, y)){return G.edge[x][y];}else{printf("该边不存在\n");returnNULL;}}//打印图voidPrintGraph(MGraph G){//打印顶点int i =0;printf("顶点数据:");while(i < MaxVertexNum && G.vex[i]>=0){printf("%c ", G.vex[i]);
i++;}printf("\n");//打印邻接矩阵printf("邻接矩阵数据:\n");for(i =0; i < MaxVertexNum; i++){for(int j =0; j < MaxVertexNum; j++){if(G.edge[i][j]>=0){printf("%d ", G.edge[i][j]);}else{printf("0 ");}}printf("\n");}printf("边数目:%d\n", G.edgenum);printf("顶点数目:%d\n", G.vexnum);}intmain(){
MGraph* G =(MGraph*)malloc(sizeof(MGraph));
G->edgenum =0;
G->vexnum =0;//G->edge = (E**)malloc(sizeof(E));//G->vex = (V*)malloc(sizeof(V));InsertVertex(*G,'a');InsertVertex(*G,'b');InsertVertex(*G,'c');InsertVertex(*G,'d');InsertVertex(*G,'e');AddEdge(*G,0,1,1);AddEdge(*G,1,0,1);AddEdge(*G,0,3,2);AddEdge(*G,3,0,2);AddEdge(*G,1,2,3);AddEdge(*G,2,1,3);AddEdge(*G,1,4,4);AddEdge(*G,4,1,4);AddEdge(*G,2,4,5);AddEdge(*G,4,2,5);AddEdge(*G,2,3,6);AddEdge(*G,3,2,6);PrintGraph(*G);RemoveEdge(*G,0,1);PrintGraph(*G);DeleteVertex(*G,'a');PrintGraph(*G);return0;}