圖的鄰接矩陣表示
阿新 • • 發佈:2020-11-17
程式碼:
#include <stdio.h> #include <stdlib.h> #define MaxVertexNum 100 // 最大頂點數設為 100 #define INFINITY 65535 // 無窮大設為雙位元組無符號整數的最大值 65535 typedef int Vertex; // 用頂點下標表示頂點, 為整型 typedef int WeightType; // 邊的權值設為整型 typedef char DataType; // 頂點存的資料型別設為字元型 // 圖節點的定義 typedef struct GNode * PtrToGNode; struct GNode { int Nv; // 頂點數 int Ne; // 邊數 WeightType G[MaxVertexNum][MaxVertexNum]; // 鄰接矩陣 DataType Data[MaxVertexNum]; // 存頂點的資料 /* 注意: 若頂點無資料, 此時 Data[] 可以不用出現 */ }; typedef PtrToGNode MGraph; // 邊的定義 typedef struct ENode * PtrToENode; struct ENode { Vertex V1, V2; // 有向邊 <v1, V2> WeightType Weight; // 權重 }; typedef PtrToENode Edge; MGraph CreateGraph(int VertexNum) { // 初始化一個有 VertexNum 個頂點但沒有邊的圖 Vertex V, W; MGraph Graph; Graph = (MGraph) malloc(sizeof(struct GNode)); // 建立圖 Graph->Nv = VertexNum; Graph->Ne = 0; // 初始化鄰接矩陣 // 注意: 這裡預設頂點編號是從 0 開始, 到 (Graph->Nv - 1) for (V = 0; V < Graph->Nv; V++) for (W = 0; W < Graph->Nv; W++) Graph->G[V][W] = INFINITY; return Graph; } 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 BuildGraph() { MGraph Graph; Edge E; // Vertex V; int Nv, i; scanf("%d", &Nv); // 讀入頂點個數 Graph = CreateGraph(Nv); // 初始化有 Nv 個頂點但沒有邊的圖 scanf("%d", &(Graph->Ne)); // 讀入邊數 if (Graph->Ne != 0) // 如果有邊 { E = (Edge)malloc(sizeof(struct ENode)); // 建立邊節點 // 讀入邊, 格式為 "起點 終點 權重", 插入鄰接矩陣 for (i = 0; i < Graph->Ne; i++) { scanf("%d %d %d", &E->V1, &E->V2, &E->Weight); // 注意: 如果權重不是整型, Weight 的讀入格式要改 InsertEdge(Graph, E); } } // 如果頂點有資料的話, 讀入資料 /*for (V = 0; V < Graph->Nv; V++) scanf("%c", &(Graph->Data[V]));*/ return Graph; } // 簡單遍歷圖 void PrintGraph(MGraph G) { int i, j; for (i = 0; i < G->Nv; i++) { for (j = 0; j < G->Nv; j++) { if (G->G[i][j] == INFINITY) { printf("∞ "); continue; } printf("%d ", G->G[i][j]); } printf("\n"); } } // 測試一組資料, 測試的圖有 5 個頂點, 8 條有向邊 // <1, 0, 9> <0, 2, 6> <2, 4, 7> <4, 3, 6> <3, 1, 5> <1, 2, 4> <0, 3, 3> <3, 4, 8> int main() { MGraph G = BuildGraph(); PrintGraph(G); return 0; } // 測試資料 /* 5 8 1 0 9 0 2 6 2 4 7 4 3 6 3 1 5 1 2 4 0 3 3 3 4 8 */
輸出結果:
參考:《資料結構第 2 版》(陳越) & 浙江大學資料結構 MOOC