用鄰接矩陣方式建立圖、簡化化版
阿新 • • 發佈:2019-02-14
//用鄰接矩陣表示圖 #include <stdio.h> #include <stdlib.h> #define MaxVertexNum 20 typedef int WeightType; typedef char DataType; typedef struct GNode *PtrToGNode; typedef PtrToGNode MGraph; //以鄰接矩陣儲存的圖型別 struct GNode { int Nv; //頂點數 int Ne; //邊數 WeightType G[MaxVertexNum][MaxVertexNum]; DataType Data[MaxVertexNum]; //存頂點的資料 }; //初始化一個有VertexNUm個頂點但沒有邊的圖 typedef int Vertex; //用頂點下標表示頂點,為整型 MGraph CreateGraph(int VertexNum) { Vertex v, w; struct GNode* Graph; Graph = (MGraph)malloc(sizeof(struct GNode)); Graph ->Nv = MaxVertexNum; Graph ->Ne = 0; //這裡的預設編號從0開始,到(Graph->Nv - 1) for (v = 0; v < Graph->Nv; v++) for (w = 0; w < Graph->Ne; w++) Graph->G[v][w] = 0; return Graph; } //向MGraph中插入邊 typedef struct ENode *PtrToENode; struct ENode { Vertex v1, v2; //有向邊<v2, v1> WeightType Weight; //權重 }; typedef PtrToENode Edge; void InsertEdge(MGraph Graph, Edge E) { //插入邊<v1, v2> Graph->G[E -> v1][E->v2] = E->Weight; //插入邊<v2, v1> Graph->G[E->v2][E->v1] = E->Weight; } //完整地建立一個MGraph MGraph BuildGraph() { MGraph Graph; Edge E; Vertex V; int Nv, i; scanf_s("%d", &Nv); Graph = CreateGraph(Nv); scanf_s("%d", &(Graph->Ne)); if (Graph->Ne != 0) { E = (Edge)malloc(sizeof(struct ENode)); for (i = 0; i < Graph->Ne; i++) scanf_s("%d %d %d", &E->v1, &E->v2, &E->Weight); InsertEdge(Graph, E); } // for (V = 0; V < Graph->Nv; V++) scanf_s(" %c", Graph->Data[V]); return Graph; } int main() { return 0; }
簡化版
//用鄰接矩陣表示圖 #include <stdio.h> #include <stdlib.h> #define MaxN 20 int G[MaxN][MaxN], Nv, Ne; void BuildGraph() { int i , j, v1, v2, w; scanf("%d", &Nv); for (i = 0; i < Nv; i++) for (j = 0; j < Nv; j++) G[i][j] = 0; scanf_s("%d", &Ne); for (i = 0; i < Ne; i++) { scanf_s("%d %d %d", &v1, &v2, &w); G[v1][v2] = w; //InsertEdge G[v2][v1] = w; } }