#pragma once
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define INFINITY 1000
#define MAXSIZE 100
typedef char InfoPtr;
typedef int VRType;
typedef enum {DG,DN,UG,UN} GraphKind;
typedef char VertexType;
typedef struct{
VRType weight;
InfoPtr info[8];//other info
}ArcNode,AdjMetrix[MAXSIZE][MAXSIZE];
typedef struct
{
VertexType vex_array[MAXSIZE];
AdjMetrix metrix;
int vertex_num;
int arc_num;
GraphKind graph_kind;
}MGraph;
void CreateGraph(MGraph * g);
int LocateVertex(MGraph g, VertexType v);
void DestroyGraph(MGraph *g);
void DisplayGraph(MGraph g);
//implementation
void CreateGraph(MGraph* g){
cout<<"1.input graph vertex num,arc num, arc info"<<endl;
int set_arc_info = 0;
cin>>g->vertex_num>>g->arc_num>>set_arc_info;
// scanf("%d,%d, %d", &(g->vertex_num), &(g->arc_num), &set_arc_info);
//set array
cout<<"2.input elements"<<endl;
for(int i = 0; i < g->vertex_num;++i){
//scanf("%c",&(g->vex_array[i]));
cin>>g->vex_array[i];
//cout<<"next"<<endl;
}
//initialize metrix
cout<<"\n3. initialize metrix each to INFINITY"<<endl;
for(int i = 0; i < g->vertex_num; ++i){
for(int j = 0; j < g->vertex_num; ++j){
g->metrix[i][j].weight = INFINITY;
}
}
//set arc
cout<<"\n 4.set arc info"<<endl;
for(int k = 0; k < g->arc_num;++k){
VertexType v1, v2;
int weight;
//scanf("%c%c%d",&v1, &v2, &weight);
cout<<"input the v1 and v2 with weight"<<endl;
cin>>v1>>v2>>weight;
int m = LocateVertex(*g,v1);
int n = LocateVertex(*g,v2);
g->metrix[m][n].weight = weight;
if(set_arc_info){
cout<<"input the arc info:"<<endl;
cin>>g->metrix[m][n].info;
}
}
//kind
g->graph_kind = DN;
}
int LocateVertex(MGraph graph, VertexType v){
for(int i = 0; i < graph.vertex_num;++i){
if(graph.vex_array[i] == v){
return i;
}
}
return -1;
}
void DestroyGraph(MGraph *graph){
}
void DisplayGraph(MGraph graph){
for (int i = 0 ; i < graph.vertex_num;++i){
//printf("%c\t",graph.vex_array[i]);
for (int j = 0; j < graph.vertex_num;++j){
if(graph.metrix[i][j].weight == INFINITY){
printf("~\t");
}else{
printf("%d\t", graph.metrix[i][j].weight );
}
}
printf("\n");
}
}
void test_adjmetrix(){
MGraph graph;
cout<<"Create a graph"<<endl;
CreateGraph(&graph);
cout<<"Print the graph:"<<endl;
DisplayGraph(graph);
cout<<"Destroy the graph"<<endl;
}
图-邻接矩阵
最新推荐文章于 2023-05-06 15:56:20 发布