#include<stdio.h>code
#include<stdlib.h>element
#define Max 10get
typedef char elementType;it
//定義圖頂點相關的內容io
typedef struct Graph_g {im
elementType peek[Max]; int number_vertex;//定義頂點個數 int nubmer_edge;//定義邊的個數 int G[Max][Max];//定義臨接矩陣 bool c[Max];
}Graph, *Graph_matrax;集合
//對圖進行初始化di
Graph_matrax init() {co
Graph_matrax graph = (Graph_matrax)malloc(sizeof(Graph)); int vertex; printf("請輸入頂點的個數\n"); scanf("%d", &vertex); graph->number_vertex = vertex; graph->nubmer_edge = 0; int i; //對頂點的信息進行賦值 for (i = 0; i < vertex; i++) { getchar(); char c; printf("請輸入%d個頂點的信息:", i + 1); scanf("%c", &c); graph->peek[i] = c; } //臨接矩陣的對腳線賦值爲0,其餘的初始化爲最大值,假設全都不連通 for (int i = 0; i < graph->number_vertex; i++) { for (int j = 0; j < graph->number_vertex; j++) { if (i == j) graph->G[i][j] = 0; else graph->G[i][j] = 8888; } } int edge = 0; int v1, v2, w; printf("請輸入邊的數目:"); scanf("%d", &edge); for (i = 0; i < edge; i++) { printf("請輸入i,j,w,有關頂點的到頂點的邊的相關信息:"); scanf("%d%d%d", &v1, &v2, &w); graph->G[v1 - 1][v2 - 1] = w; graph->G[v2 - 1][v1 - 1] = w; } return graph;
}display
void display(Graph_matrax g) {
printf("輸出臨接矩陣:\n"); for (int i = 0; i < g->number_vertex; i++) { for (int j = 0; j < g->number_vertex; j++) { printf("%8d", g->G[i][j]); } printf("\n"); }
}
void Prim(Graph_matrax g, int v) {
//lowcost存儲爲放到集合到已經放到集合的最小值,lowcost[i]=0表示該i節點己經放到集合中了,也能夠做爲後面判斷有環的條件 int lowcost[Max]; int close[Max];//存儲誰指向本身的節點,也就是該節點的父親 int i; //初始化,第一個放入的節點 for (i = 0; i < g->number_vertex; i++) { lowcost[i] = g->G[v][i]; close[i] = v; } int min; int k=0; int j; //把另外的n-1元素作相同的操做 for (i = 1; i < g->number_vertex; i++) { min = 8888888; //找到還未放到集合到集合某個節點的最小權值的節點 for (j = 0; j < g->number_vertex; j++) if (lowcost[j] != 0 && min >lowcost[j]) { min = lowcost[j]; k = j; } printf("%d->%d 權重爲%d ",close[k], k,lowcost[k]); //放入到集合的元素要把權值放置爲0 lowcost[k] = 0; //在剛找的節點的臨接點中的最小權值,與lowcost[]中的比較,小就更新 for (j = 0; j < g->number_vertex; j++) { if (g->G[k][j] != 0 && g->G[k][j] < lowcost[j]) { lowcost[j] = g->G[k][j]; //把父親節點存入進去 close[j] = k; } } printf("\n"); }
}
int main() {
Graph_g *g = init(); printf("%d\n", g->number_vertex); display(g); printf("\n"); //爲了不出現錯誤,把c[]所有設爲false Prim(g, 0); printf("\n"); system("pause"); return 0;
}