Data Structure-prim (prim) algorithm for Minimum Spanning Tree in C Language
// Prim algorithm of minimum spanning tree
// Yang Xin
#include
#include
#define n 6
#define MaxNum 10000 / * Define a maximum integer * /
/ * Define adjacency matrix type * /
typedef int adjmatrix [n + 1] [n + 1]; / * Unit 0 is useless * /
typedef struct
{
int fromvex, tovex; // start and end of spanning tree
int weight; // weight of the edge
} Edge;
typedef Edge * EdgeNode; // Define alias of spanning tree
int arcnum; / * number of edges * /
/ * Build graph adjacency matrix * /
void CreatMatrix (adjmatrix GA)
{
int i, j, k, e;
printf (===============================
);
printf (% d vertices in the picture
, n);
for (i = 1; i <= n; i ++)
{
for (j = 1; j <= n; j ++)
{
if (i == j)
{
GA [i] [j] = 0; / * Set the diagonal value to 0 * /
}
else
{
GA [i] [j] = MaxNum; / * The value in other positions is initialized to a maximum integer * /
}
}
}
printf (Please enter the number of edges:
);
scanf (% d, & arcnum);
printf (Please enter the information of the edge, in the form of starting point, ending point, and weight:
);
for (k = 1; k <= arcnum; k ++)
{
scanf (% d,% d,% d, & i, & j, & e); / * Read the edge information * /
GA [i] [j] = e;
GA [j] [i] = e;
}
}
/ * Initialize the edge set array of the graph * /
void InitEdge (EdgeNode GE, int m)
{
int i;
for (i = 1; i <= m; i ++)
{
GE [i] .weight = 0;
}
}
/ * Generate graph edge set array based on graph's adjacency matrix * /
void GetEdgeSet (adjmatrix GA, EdgeNode GE)
{
int i, j, k = 1;
for (i = 1; i <= n; i ++)
{
for (j = i + 1; j <= n; j ++)
{
if (GA [i] [j]! = 0 && GA [i] [j]! = MaxNum)
{
GE [k] .fromvex = i;
GE [k] .tovex = j;
GE [k] .weight = GA [i] [j];
k ++;
}
}
}
}
/ * Arrange the edge set array of the graph in ascending order * /
void SortEdge (EdgeNode GE, int m)
{
int i, j, k;
Edge temp;
for (i = 1; i GE [j] .weight)
{
k = j;
}
}
if (k! = i)
{
temp = GE [i];
GE [i] = GE [k];
GE [k] = temp;
}
}
}
/ * Use Prim algorithm to find the minimum spanning tree of the graph represented by the adjacency matrix starting from the initial point v * /
void Prim (adjmatrix GA, EdgeNode T)
{
int i, j, k, min, u, m, w;
Edge temp;
/ * Assign an initial value to T, corresponding to the edges of v1 to the remaining vertices in turn * /
k = 1;
for (i = 1; i <= n; i ++)
{
if (i! = 1)
{
T [k] .fromvex = 1;
T [k] .tovex = i;
T [k] .weight = GA [1] [i];
k ++;
}
}
/ * Loop n-1 times, each time to find the k-th edge in the minimum spanning tree * /
for (k = 1; k
result: