“ Ctrl AC!一起 AC!”
图的建立
用邻接矩阵表示图:
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; //顶点数
int Ne; //边数
WeightType G[MaxVertexNum][MaxVertexNum];
//DataType Data[MaxVertexNum] /*存顶点*/
};
typedef PtrToGNode MGraph;
初始化一个有VertexNum个顶点但没有边的图:
typedef int Vertex;
MGraph CreateGraph(int VertexNum){
Vertex V,W;
MGraph Graph;
Graph=(MGraph)malloc(sizeof(struct GNode));
Graph->Nv=VertexNum;
Graph->Ne=0;
for(V=0;V<Graph->Nv;V++){
for(W=0;W<Graph->Nv;W++){
Graph[V][W]=0;
}
}
return Graph;
}
边的定义:
typedef struct ENode* PtrToENode;
struct ENode{
Vertex V1,V2;
WeightType Weight;
};
typedef PtrToENode Edge;
插入边:
void InsertEdge(MGraph Graph,Edge E){
/*插入边<V1,V2>*/
Graph->G[E->V1][E->V2]=E->Weight;
/*若是无向图,还需反插*/
Graph->G[E->V2][E->V1]=E->Weight;
}
完整建立:
MGraph BuildGraph(){
MGraph Graph;
Edge E;
Vertex V;
int Nv,i;
cin>>Nv;
Graph=CreateGraph(Nv);
cin>>Graph->Ne;
if(Graph->Ne!=0){
E=(Edge)malloc(sizeof(struct ENode));
for(i=0;i<Graph->Ne;i++){
cin>>E->V1>>E->V2>>E->weight;
InsertEdge(Graph,E);
}
}
/*如果顶点有数据*/
for(V=0;V<Graph->Nv;V++){
cin>>Graph->Data[V];
}
return Graph;
}
用邻接表表示图:
邻接表的定义:
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV; //邻接点下标
WeightType Weight;
PtrToAdjVNode Next;
};
typedef struct VNode{
PtrToAdjVNode FirstEdge;
DataType Data //存顶点的数据
}AdjList;
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G[MaxVertexNum];
};
typedef PtrToGNode LGraph;
初始化无边图:
typedef int Vertex;
LGraph CreateGraph(int VertexNum){
Vertex V,W;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv=VertexNum;
Graph->Ne=0;
for(V=0;V<Graph->Nv;V++){
Graph->G[V].FirstEdge=NULL;
}
return Graph;
}
插入边:
感谢阅读!!!
“ Ctrl AC!一起 AC!”